Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Introduction to C#

Posted by Ravi Varma Thumati on February 12, 2015

What is C# Programming Language?

C# is a simple, modern, object oriented programming language derived from C and C++. C# (pronounced “C sharp”) is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers.

C# includes all the support for structured, component- based, object-oriented programming that you expect of a modern language built on the shoulders of C++. C# is a case-sensitive language: Incorrect case prevents the code from compiling successfully.

Structure of a C# Program:

// Namespace Declaration
using System;
class Sample
{
public static void Main()
{
// Write to console
Console.WriteLine (“Welcome to C# Programming!”);
}
}

In this program, you will display some text to the screen. Compiling and running this code displays the words “Welcome to C# Programming!” at the console. Before we compile and run it, let’s first take a closer look at this simple program.

The “Sample” program declares a single type: the Sample class. To define a C# type, you declare it as a class using the class keyword, give it a name in this case “Sample”. The properties and behavior definitions of C# class must be enclosed by open and closed braces { }.

The using Keyword

Rather than writing the word System before Console, you could specify that you will be using types from the System namespace by writing the directive:

using System;

Example The using keyword

using System;class Hello{    static void Main( )    {        //Console from the System namespace        Console.WriteLine(“Hello World”);    }}

The using System; directive references a namespace called System that is provided by the .NET runtime. The using statement tells the compiler to search this namespace when resolving references, making it unnecessary to use fully qualified names. For example, you can refer to label rather than System.Web.UI.WebControls.Label.

Notice the using System directive is placed before the Hello class definition.

The Main() Method

A Main() method is required for every executable C# application. This method serves as the entry point to the application; it must always have the static modifier and the M must be capitalized. Overloaded forms of Main ()define a return type and accept a parameter list as input  Return an integer value:

static int Main(){               return 0; // must return an integer value}

Receive a list of command-line arguments as a parameter and return an integer value:

static int Main(string[] args){      // loop through arguments      foreach(string myArg in args)               Console.WriteLine(myArg);               return 0;}

The parameter is a string array containing the contents of the command line used to invoke the program. For example, this command line executes the program MyApparel and passes it two parameter values:

C:\> MyApparel 5 6

The static keyword

The Main( ) method shown in above code has one more designation. Just before the return type declaration void (which, you will remember, indicates that the method doesn’t return a value) you’ll find the keyword static:

static void Main()

The static keyword indicates that you can invoke Main( ) without first creating an object of type Hello.

The Dot (.) Operator

In above code, the dot operator (.) is used both to access a method in a class (in this case, the method WriteLine( )), and to restrict the class name to a specific namespace (in this case, to locate Console within the System namespace). This works well because in both cases we are “drilling down” to find the exact thing we want. The top level is the System namespace (which contains all the System objects that the FCL provides); the Console type exists within that namespace, and the WriteLine() method is a member function of the Console type.

In many cases, namespaces are divided into subspaces. For example, the System namespace contains a number of subnamespaces such as Data, Configuration, Collections, and so forth, while the Collections namespace itself is divided into multiple subnamespaces.

Namespaces can help you organize and compartmentalize your types. When you write a complex C# program, you might want to create your own namespace hierarchy, and there is no limit to how deep this hierarchy can be. The goal of namespaces is to help you divide and conquer the complexity of your object hierarchy.

Compiling and Running the C# Program

To compile the program, you can use Visual Studio or the command-line compiler.

Using Command-line Compiler:

To use the command-line compiler, in its simplest form, Open a .NET command window (Start -> Programs -> Visual Studio .NET -> Visual Studio Tools -> Visual Studio Command Prompt. Use the following command:

csc SampleProgram.cs

In this command, csc is the name of the command-line compiler and SimpleProgram.cs is the name of the source file.

This step builds the EXE file. If the program contains errors, the compiler reports them in the command window. The /debug command-line switch inserts symbols in the code so that you can run the EXE under a debugger or see line numbers in stack traces. (You’ll get a stack trace if your program generates an error that you don’t handle.)

To run the program under .NET, enter: SampleProgram

You should now see the venerable words “Hello World” appear in your command window.

Selected Options for the C# Command-Line Compiler
Option Description
/addmodule Specifies a module that is to be included in the assembly created. This is an easy way to create a multi-file assembly.
/debug Causes debug information to be produced.
/define Preprocessor directive can be passed to compiler: /define:DEBUG.
/delaysign Builds an assembly using delayed signing of the strong name.
/doc Used to specify that an output file containing XML documentation is to be produced.
/keyfile Specifies the path to the .snk file containing the key pair used for strong signing.
/lib Specifies where assemblies included in the /reference option are located.
/out Name of the file containing compiled output. The default is the name of the input file with .exe suffix.
/reference (/r) References an external assembly.
/resource Used to embed resource files into the assembly that is created.
/target (/t) Specifies the type of output file created:

/t:exe builds a *.exe console application. This is the default output.

/t:library builds a *.dll assembly.

/t:module builds a module (Portable Executable file) that does not contain a manifest.

/t:winexe builds a *.exe Windows Forms assembly.

 Using Visual Studio IDE:

There are many ways to compile and run the “Hello World” program from within Visual Studio. Typically you can accomplish every task by choosing commands from the Visual Studio menu toolbar, by using buttons, and, in many cases, by using key-combination shortcuts.

For example, to compile the “SampleProgram” program, press Ctrl-Shift-B or choose Build Build Solution. As an alternative, you can click the Build button on the Build toolbar

 Build toolbar

 To run the “SampleProgram” program without the debugger, you can press Ctrl-F5 on your keyboard, choose Debug -> Start Without Debugging from the IDE menu toolbar, or press the Start Without Debugging button on the IDE Build toolbar. You can run the program without first explicitly building it; depending on how your options are set (Tools -> Options), the IDE will save the file, build it, and run it, possibly asking you for permission at each step.

Reading and Writing to Console:

In this chapter, we already used System.Console.WriteLine for writing out text to the command console. In addition to being able to write out data, a program needs to be able to accept data that a user may enter.

One of the ways to retrieve text that is entered at the console is to use System.Console.ReadLine(). This method stops the program execution so that the user can enter characters. When the user presses the Enter key, creating a newline, the program continues. The output, also known as the return, from the System.Console.ReadLine() method is the string of text that was entered.

Using System.Console.ReadLine()

class HeyYou{         static void Main()        {                string firstName;                string lastName;                 System.Console.WriteLine(“Hey you!”);                 System.Console.Write(“Enter your first name: “);                firstName = System.Console.ReadLine();                 System.Console.Write(“Enter your last name: “);                lastName = System.Console.ReadLine();                 …       }}

After each prompt, this program uses the System.Console.ReadLine() method to retrieve the text the user entered and assign it to an appropriate variable. By the time the second System.Console.ReadLine() assignment completes, firstName refers to the value Inigo and lastName refers to the value Montoya.

System.Console.Read()

In addition to the System.Console.ReadLine() method, there is also a System.Console.Read() method. However, the data type returned by the System.Console.Read() method is an integer corresponding to the character value read, or 1 if no more characters are available. To retrieve the actual character, it is necessary to first cast the integer to a character.

Using System.Console.Read()

int readValue;char character;readValue = System.Console.Read();character = (char) readValue;System.Console.Write(character);

In C# 2.0, there is a new method called System.Console.ReadKey() which, in contrast to System.Console.Read(), returns the input after a single keystroke. It enables the developer to intercept the keystroke and perform actions, such as restricting the characters to numerics.

Writing Output to the Console

In prvious example you prompt the user for his first and last names using the method System.Console.Write() rather than System.Console.WriteLine(). Instead of placing a newline character after displaying the text, the System.Console.Write() method leaves the current position on the same line. In this way, any text the user enters will be on the same line as the prompt for input.

class HeyYou{  static void Main()  {      string firstName;      string lastName;      System.Console.WriteLine(“Hey you!”);       System.Console.Write(“Enter your first name: “);      firstName = System.Console.ReadLine();       System.Console.Write(“Enter your last name: “);      lastName = System.Console.ReadLine();       System.Console.WriteLine(“Your full name is {0} {1}.”,                            firstName, lastName);                                                  }}

Swapping the Indexed Placeholders and Corresponding Variables

System.Console.WriteLine(“Your full name is {1}, {0}”,  firstName, lastName);

Two ways to write to console

  1. Concatenation
  2. Placeholder syntax

string UserName = Console.ReadLine();
// Concatenate name with hello word and print
Console.WriteLine(“Hello ” + UserName);

//Placeholder syntax to print name with hello word
Console.WriteLine(“Hello {0}”, UserName);

Leave a comment