C# Tutorial – Application input, output & error streams


Sometimes an application needs to print data / let user know something. It might also needs to get data from an user. In this post I’ll show you few basic ways to communicate.

Standard output and error output

First you have to know that every application has 2 output streams:

  • Standard output – Used to report regular data. For example, let’s say that you have an application that prints your tasks. The standard output is a perfect place where your application can print the tasks.
  • Error output – Used for providing details about unexpected situations. Let’s say that an application crashed – error output is the best place to put information about the error.

You might wonder if it’s so common why didn’t you noticed it? Usually application that output something is executed in a console. The console is reading data from both standard output and error output and prints it the same way. More, some application don’t differentiate outputs and put everything to a standard output.

Standard output

Ok, let’s now have a look on how to print something to standard output. In .NET Framework there is special class – System.Console  that is responsible for handling console operations. In C# Hello World post you can find a good example:

Console.WriteLine("Hello, World!");

The WriteLine  method prints specified argument to application standard output. There is similar method – Write  – it does almost the same. The only difference is that WriteLine  adds new line characters.

Here you can find all Console class methods – for example Console.Beep().

Error output

There is very similar way to use error output.

Console.Error.WriteLine("An error");

Reading from the Console

If there is standard output, you might suspect that there is standard input as well. That’s correct. The easiest way to read it is to use System.Console  class again.

string line = Console.ReadLine();

Console interactive example

Now, you can read and write to the console. This way you can create your fist interactive application. Here is a short example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
    class Program
        static void Main(string[] args)
            Console.Write("Please enter your name: ");
            string name = Console.ReadLine();
            Console.WriteLine("Hi " + name);

Then, press Ctrl+F5.

Please enter your name: Mariusz
Hi Mariusz
Press any key to continue . . .

That’s all :)



Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

4 thoughts on “C# Tutorial – Application input, output & error streams