Basic Concepts of C#

Introduction

Like the C++ language, C# is an Object Oriented programming language. Generally many people spell C# as C#.Net (C Sharp dot Net), but here Microsoft developed the .Net environment mainly for distributed applications (the sharing of processing between client and server) and in C#.Net "Net" indicates that C# is used to develop only Distributed Applications but using C# we can develop any kind of software applications including Windows applications.

C# is a new language especially developed from scratch to work with the .NET environment. Using C# we can write a webpage, XML based applications like web services, Components for distributed applications as well as desktop applications.

Writing First C# Program

Writing a program in the C# language is similar to writing in the traditional C++ language. If you are familiar with the C++ language its easy you to write and understand C# Code. Anyway I will explain every line in our basic First C# program where we will cover the things used for writing and understanding simple to complex programs. Let's look at our first C# program.

Program 1-1

using System;
namespace sai.CS
{
    class FirstCSProgram
    {
        static void Main()
        {
            Console.WriteLine("This Is Our First CSharp Program.");
             Console.ReadLine();
             return;
        }
    }
}

Compiling and Executing the Program

The above Program can be written using any text editor like notepad, editplus, vi editor (in Linux) etc.., or we can use the Visual Studio's .NET IDE (Integrated Development Environment) designed by Microsoft especially to write, compile and execute the .NET compatible languages. C# is one of the .NET compatible languages; the other compatible .NET languages are VB.NET, J# etc.

There are two ways of compiling the above C# Program.

  1. If you write this Program in Visual Studio's .NET IDE, then there is no additional work to do to compile and execute the application. Just use function key F5 or go to the <Debug> Menu and select <Start Debugging>. The IDE internally complies and executes the application without any user interaction.

  2. In this method we manually compile and execute the above application using the Command Prompt. Now open your command prompt (Start->Run->cmd or command). You can compile the program by simply using the C# compiler Tool (csc.exe) as shown below:

Csc FirstCSProgram.cs

When you press the <Enter> Key this csc.exe tool will compile our application named FirstCSProgram.cs and create an exe file with the same file name, such as FirstCSProgram.exe.

Now type "FirstCSProgram.exe" (with or without quotes) in your command prompt to execute our sample first C# program.

Note: cs is the file extension for C# applications.

Important point: Before using the tools such as csc.exe in your command prompt you have to set some environmental variables. To set these environmental variables, you have two choices; first, you can run a batch file named vcvars32.bat which is located in the <Microsoft Visual Studios folder>/common7/Tools folder (here <Microsoft Visual Studios folder> is the location where your Visual Studio is installed). Second, you will find a <Visual Studios 2005 or 2008> command prompt in the Start Menu ->programs -> Microsoft Visual Studios 2005 or 2008 -> Visual Studios Tools-> Visual Studio 2005 or 2008 command prompt which automatically sets up these environmental variables for you. So you can directly use the .NET tools here

A Close Look at the Code

Line 1: The first line of our sample program is:

using System;

Here we are importing the namespaces using the <using> keyword. In the above statement, system is the namespace and we are importing it into our program. I will explain what this namespace is and how to use it and its importance in our next session; for now just remember that a namespace is a group of similar types of items and every class should belong to a specific namespace.

Line 2: Our next line in our program defines a namespace to our class as shown below:

namespace sai.CS

Here we define a namespace forour class by simply writing a user-defined namespace name preceded with the <namespace> keyword.

Line 3: The Opening flower brace ({) indicates to the compiler that the block is opened or started; it is similar to its use in the C++ programming Language. When the compiler encounters this opening brace it will crease a new space on the stack memory where it will declare the variable which is scoped to that block only (in the next chapter I will explain about variables, declaring variables and their scopes) and allocating some memory from that newly created space for that block. Like when the compiler maintains n number of variables in memory.

Line 4: In line 4 of our program we are declaring the class and its name as shown below:

class FirstCSProgram

In C# programming, whatever the business logic is that you want to write, it should be in a class block. I will explain what a lass is and its uses in our future chapters so don't worry abou that; for now just remember that whatever you want to write should be written in a class block and every program should contain at least one class. A class optionally contains variables and optionally methods or functions; here we can define a class by simply writing a user-defined class name preceded with the "class" keyword.

Line 5: is an opening flower brace ({) as I explained above in line 3, but this opening brace indicates to the compiler a class block to be opened.

Line 6: As I said in the above line, that is a class optionally containing variables and optionally containing methods or functions; here now in line 6 we defined a function or method as shown below:

static void Main()

One important point you should note is that a program can contain multiple classes under one namespace but in that class at least one class should contain this Main() method because the compiler starts its job from this Main() function; if you do not have this function in your program then the compiler cannot compile your program because it doesn't know from where it should start compiling and instead just raises an error. So you can define a Main() method as we defined in our program.

Note: A deep discussion on this Main() method and their uses will be in future chapters.

Line 7: An opening flower brace ({) as I explained above for lines 3 & 5, but this brace indicates to the compiler that the Main() method block has opened.

Line 8: This is the first statement in our Main() method. Note that every statement should end with a semicolon (;). Here in the following statement, Console is the class in the System namespace as explained above and WriteLine() is a static method. I will explain later what the difference is between a static method and a normal method; for now just remember that static methods are called directly by its class name as in this case. In the code WriteLine() is the method we are sending the text "This Is Our First CSharp Program.". When the compiler reads this line it just prints the text "This Is Our First CSharp Program." on the command prompt at runtime.

Console.WriteLine("This Is Our First CSharp Program."); 

Note: A Console class is designed to read and print or write a text on the console; i.e., in a command prompt, this class contains functions that are used to read and print text on the console.

In the Console class we have two methods to print text in the command prompt. There are WriteLine() and Write() methods. Both print the text on the screen but the WriteLine() method prints the text followed by a new line character (\n); with this, every WriteLine() method writes text on separate new lines. For example:

Console.Write ("This Is First Line.");
Console.Write ("This Is Second Line.");

The output will be

1.jpg

In the same example, replace the WriteLine() method with the Write() method as shown below:

Console.Write ("This Is First Line.");
Console.Write ("This Is Second Line.");

The output will be:

2.jpg

Line 9: As we know by the above discussion of the Console class we said that we can read and print the text on the console; above we came to know how we can print a text on the console screen but how will we read text written by a user at runtime? The answer is, as I said, that the Console class has functionality for reading and printing text, as we have seen to print the text on the screen we used the WriteLine() and Write() methods in the Console class. To read we have another method, ReadLine(); the name itself resembles the functionality of this method i.e.., it reads the text which is entred by the user at runtime.

Console.ReadLine(); 

Let's take one example program to understand how the ReadLine() method works and its importance. Here in this example we accept two numbers from the user ar runtime and we print the sum of the two numbers. Here is the Program:

using System;
namespace FirstCSprogram
{
    class Program
    {
        static void Main()
        {
            int a, b;
            Console.Write("Enter First Number : ");
            a = int.Parse(Console.ReadLine());
            Console.Write("Enter First Number : ");
            b = int.Parse(Console.ReadLine());
            Console.WriteLine("The Sum Of {0} and {1} Is : {2}", a, b, (a + b).ToString());
            Console.ReadLine();
        }
    }
}

When you compile and run this program in a console it will ask you to enter the first number; after entering the fist number and pressing enter, again it prompts for the second number; after giving the second number it will calculate the sum of these two numbers and display the result on the console.

Here is how the output screen will look like:

3.jpg

Note: Since we have the ReadLine() to read a line of text, similarly we have another method Read() which reads the next character on the input stream.

Line 10: The next statement is:

return; 

This statement indicates to the compiler that the end of the scope of its belonging Block. It returns the control to its calling method which is waiting for this control on the stack memory.

Line 11, 12, and 13: These three lines indicate the end of their correspondingblock. As I explained, the opening of the block is represented by opening flower braces ({); similarly the closing of the block is represented by closing flower braces (}).


Similar Articles