C# Beginners: Basics input and output methods

In this tutorial, you will be learning about input and output methods in C#.

You will learn how the user can get the input from standard input and display the same in standard output using C#.

Learning Basics input and output methods in C#

To output something in C#, we can use

System.Console.WriteLine()   //prints in newline

or

System.Console.Write()  //prints on same line

To get input from user in C#, we can use

System.Console.ReadLine() //Reads the next line of input from standard input stream

System.Console.Read()     //Reads the next character from the standard input stream 

System.Console.ReadKey()  //Obtains the next key pressed by user.This method usually used to hold the screen until user presses a key

Note:
  • Here, System is a namespace. Console is a class within namespace System. Writeline(), Write(), ReadLine(), Read() and ReadKey() are the methods of the class Console.
  • Namespace System can be omitted i.e System.Console.Write() is same as Console.Write().

Let us take a simple example:

Getting a string as an input from the user and displaying the same.

using System; 
namespace Sample 
{  
    class codespeedy
    {
        public static void Main(string[] args) 
        { 
            Console.WriteLine("Enter a string:");  
            string str= Console.ReadLine(); 
           Console.WriteLine("You have entered:{0}",str); 
        } 
        
    } 
}

Output:

Enter a string:
Codespeedy
You have entered:Codespeedy

From the above program, you can see that

Console.WriteLine("You have entered:{0}",str);

Here, {0} is a placeholder for variable ‘str’ which will be replaced by value of  ‘str’.  You can use multiple variable also.

The line of code also written as  (by using string concatenation):

Console.WriteLine("You have entered:"+str);

Reading Numerical Values from user

Console.Readline() method receives the input as a string. It can be converted into an integer or Floating point.

One simple approach for converting is by using the Parse method.

Let  us take a simple example:

using System;

namespace Sample 
{  
    class codespeedy
    {
        public static void Main(string[] args) 
        { 
            System.Console.WriteLine("Enter a number:");  
            int intval=int.Parse(Console.ReadLine());
            System.Console.WriteLine("Enter a float number:");
            double dobval=double.Parse(Console.ReadLine());
            Console.WriteLine("Interger Number:{0}\nFloat Number:{1}",intval,dobval);
        }
    } 
}    

Output:

Enter a number:
123
Enter a float number:
123.89
Integer Number:123
Float Number:123.89

Hope, you have understood the basic input and output methods in C#.

Also, see,

Java Program to Convert OutputStream to String

Difference or Gap of days between two given dates using C#

Leave a Reply

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