Search Results

Wednesday, April 8, 2009

Basic Input/Output With the Console Class

Here i have written a program that takes name and age as an input and displays it on the Console by changing the color of the text...
//***********************************************************************************//
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("******Basic console I/O********");
GetUserData();
Console.ReadLine();

}
static void GetUserData()
{
//Get Name and Age
Console.Write("Please Enter Your Name");
string userName = Console.ReadLine();

Console.Write("Please Enter Your Age");
string userAge = Console.ReadLine();

//Change echo color,just for fun
ConsoleColor prevColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Green;

//Echo to the Console
Console.WriteLine("Hello {0} You are {1} years old.",userName,userAge);

//Restore Previous Color
Console.ForegroundColor = prevColor;
}
}
}
//*******************************************************************************//
InPut:
Enter Your Name Faisal
Enter Your Age
OutPut:
Hello Faisal You are 21 Years Old.(color will be changed to green)


NOTE:


Here in this line one thing to notice is {0} and {1}...

The question is why we are using it in Console.ReadLine()??

The reason we are using is this that Console.ReadLine( ) works just like an array of strings.whatever you input first goes to the first index of Console.ReadLine() and so on...

Or we can say that all the inputs given from the Console is saved in a temporary array of strings,
which we used in Console.WriteLine()

Remember that its index always start from 0,1,2,....


You can also repeat the index {0} , {0} in Console.WriteLine

Console.WriteLine("{0},Number {0},Number{0}",9")

No comments:

Post a Comment