System.Console

It is true that a console user interface (CUI) may not be as enticing as a graphical user interface (GUI) or web application, restricting the early examples to console programs will allow you to keep focused on the syntax of C# and the core aspects of the .NET platform, rather than dealing with the complexities of building desktop GUIs or web sites.As its name implies, the Console class encapsulates input, output, and error-stream manipulations for console-based applications.

As you can see in below table the Console class does provide some members that can spice up a simple command-line application, such as the ability to change background and foreground colors and issue beep noises in a variety of frequencies.

Members of System.Console

Member Meaning
Beep() This method forces the console to emit a beep of a specified frequency and duration.
BackgroundColor,ForegroundColor These properties set the background/foreground colors for the current output.They may be assigned any member of the ConsoleColor enumeration.
BufferHeight,BufferWidth These properties control the height/width of the console’s buffer area
Title This property gets or sets the title of the current console.
WindowHeight, WindowWidth, WindowTop, WindowLeft These properties control the dimensions of the console in relation to the established buffer.
Clear() This method clears the established buffer and console display area.

Basic Input-Output

In addition to the members in above Table, the Console type defines a set of methods to capture input and output, all of which are static and are, therefore, called by prefixing the name of the class (Console) to the method name. As you know, WriteLine() pumps a text string (including a carriage return) to the output stream. The Write() method pumps text to the output stream without a carriage return. ReadLine() allows you to receive information from the input stream up until the Enter key is pressed, while Read() is used to capture a single character from the input stream.

Create a new Console Application project to understand basic I/O using the Console class and update your Main() method to call a helper method named GetInfo().Implement this method within the Program class with logic that prompts the user for some bits of information and echoes each item to the standard output stream. For example, you could ask the user for a name and age which will be treated as a text value for simplicity, rather than the expected numerical value for now.

Program


using System;

public class ConsoleApp
{
    public static void Main(string[] args)
    {
        GetInfo();
        Console.ReadLine();
    }

    static void GetInfo()
    {
        //read the data and store it in variable age and name
        Console.Write("Enter your name: ");
        string name = Console.ReadLine();
        Console.Write("Enter your age: ");
        string age = Console.ReadLine();

        //chnages the console color 
        ConsoleColor PrevColor = Console.BackgroundColor;
        Console.BackgroundColor = ConsoleColor.Red;

        Console.WriteLine("Name: {0}", name);
        Console.WriteLine("Age: {0}", age);

        //changes the console color again
        Console.BackgroundColor = ConsoleColor.Black;
    }
}
  
  

Output


Enter your name: Hansraj
Enter your age: 20
Name: Hansraj
Age: 20
  
Visual Studio supports a number of “code snippets” that will insert code once activated. The cw code snippet is quite useful. In that it will automatically expand to Console. WriteLine()! To test this for yourself, type in cw somewhere within your Main() method and hit the Tab key twice. sadly, there is no code snippet for Console.ReadLine()). To see all code snippets, right-click in a C# code file and choose the Insert Snippet menu option.

Formatting Console output

You might have noticed numerous occurrences of tokens such as {0} and {1} embedded within various string literals. The .NET platform supports a style of string formatting slightly akin to the printf() statement of C. Simply put, when you are defining a string literal that contains segments of data whose value is not known until runtime, you are able to specify a placeholder within the literal using this curly-bracket syntax. At runtime, the values passed into Console.WriteLine() are substituted for each placeholder. The first parameter to WriteLine() represents a string literal that contains optional placeholders designated by {0}, {1}, {2}, and so forth. Be aware that the first ordinal number of a curly-bracket placeholder always begins with 0. The remaining parameters to WriteLine() are simply the values to be inserted into the respective placeholders.

 If you have more uniquely numbered curly-bracket placeholders than fill arguments, you will receive a format exception at runtime. However, if you have more fill arguments than placeholders, the unused fill arguments are ignored.

It is permissible for a given placeholder to repeat within a given string. For example

Program


using System;

public class ConsoleApp
{
    public static void Main(string[] args)
    {
        Console.WriteLine("{0}? I love {0}, I love to code in {0}", ".NET");
        Console.ReadLine();
    }
}
  
  

Output


.NET? I love .NET, I love to code in .NET
  
Also, know that it is possible to position each placeholder in any location within a string literal, and it need not follow an increasing sequence. For example,

Program


using System;

public class ConsoleApp
{
    public static void Main(string[] args)
    {
        Console.WriteLine("I am {1}.My age is {0}",20,"Hansraj");
        Console.ReadLine();
    }
}
  
  

Output


I am Hansraj.My age is 20
  

Formatting numerical data in C#

If you require more elaborate formatting for numerical data, each placeholder can optionally contain various format characters.Various format characters are given below:
Format character Meaning
C or C Used to format currency. By default, the flag will prefix the local cultural symbol (a dollar sign [$] for U.S. English)
D or d Used to format decimal numbers. This flag may also specify the minimum number of digits used to pad the value
E or e Used for exponential notation. Casing controls whether the exponential constant is uppercase (E) or lowercase (e)
F or f Used for fixed-point formatting. This flag may also specify the minimum number of digits used to pad the value
G or g Stands for general. This character can be used to format a number to fixed or exponential format
N or n Used for basic numerical formatting (with commas)
X or x Used for hexadecimal formatting. If you use an uppercase X, your hex format will also contain uppercase characters

Program


using System;

public class ConsoleApp
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Currency format: {0:c}", 1000);
        Console.WriteLine("Decimal format: {0:d6}", 9999);
        Console.WriteLine("Exponential upper: {0:E}", 9999);
        Console.WriteLine("Exponential lower: {0:e}", 9999);
        Console.WriteLine("Fixed point: {0:f3}",9999.12345);
        Console.WriteLine("Genralformat: {0:g3}",9999.12345);
        Console.WriteLine("Hex format upper: {0:X}",9999);
        Console.WriteLine("Hex format lower: {0:x}",9999);
        Console.ReadLine();
    }
}
  
  

Output


Currency format: ¤1,000.00
Decimal format: 009999
Exponential upper: 9.999000E+003
Exponential lower: 9.999000e+003
Fixed point: 9999.123
Genralformat: 1e+04
Hex format upper: 270F
Hex format lower: 270f
  
Be aware that the use of the .NET string formatting characters is not limited to console programs. This same formatting syntax can be used when calling the static string.Format() method. This can be helpful when you need to compose textual data at runtime for use in any application type (e.g., desktop GUI app, ASP.NET web app, and so forth).

The string.Format() method returns a new string object, which is formatted according to the provided flags. After this point, you are free to use the textual data as you see fit. For example, assume you are building a graphical WPF desktop application and need to format a string for display in a message box. The following code illustrates how to do so, but be aware that this code will not compile until you reference the PresentationFramework.dll assembly.

To reference PresentationFramework.dll click on Project>Add reference..>choose the library which you want to add in your program

For now add PresentationFramework.dll in your program.

Program


using System;

public class ConsoleApp
{
    public static void Main(string[] args)
    {
        //use string.Format() to format string literal
        string msg = string.Format("Hex value of 9999 is {0:f}",9999);
        /*You need to reference PresentationFramework.dll 
         * in order to compile this line of code! */
        System.Windows.MessageBox.Show(msg);
    }
}
  
  
To see the output copy this program in visual studio.Don't forget to add PresentationFramework.dll library and run the program.

Comments

Popular posts from this blog

System.Environment

Datatype and keyword