03 - Introduction to C#

3.1Structure of C# Program

The C# program contains one or more files. Each file contains one or more namespaces. A namespace consists of types such as classes, structs, interfaces delegates and enumerations. The structure of C# program that contains the elements is as shown below:

using System;
namespace Namespace1
{
    class Class1
    {
    }
    struct Struct1
    {
    }
    interface MyInterface
    {
    }
    delegate int MyDelegate();    
    enum Enum1
    {
    }    
    namespace NestedNamespace1
    {
        struct Struct2
        {
        }
    }   
    class MainClass
    {
        static void Main ( string[ ] args )
        {
            //Program code
        }
    }
}

3.2 Namespace and Class

Namespaces are used to organize the classes contained in .Net Framework. User can control the scope of class and methods names by creating user namespaces in the application. The application begins with a section using directives. The lists of namespaces that application will be using constantly can be saved by specifying a fully qualified name every time the method is contained within the use.

The general syntax of the namespace is as shown below:

     namespace namespace_name
     {
       //code declarations
     }

 

Namespace has the following properties as mentioned below:

1) They are used for managing large code projects1.2 Namespace and Class

2) The operator is used as delimiter in the namespace

3) The namespace for every class is specified by adding the using directive

4) The global namespace is the root namespace and can be referred by using the global::System namespace. It will always refer to the .Net framework namespace system

A class is a construct that enables to create custom types by using variables and other types, methods and events. It is used to define the data and behavior of the type in the application. The variables added remain in the memory until all the references are out of the scope of the application. The CLR marks the variable suitable for garbage collection.

Classes are declared by using the class keyword as shown below:

      public class Student
      {
     //fields, properties, methods, events, etc…
     }

The access level is specified before the class keyword in the declaration. The name of the class is followed by the class keyword. The behavior of the class is defined in the body of the class. The fields, properties, methods, and events are referred as class members.

A class is used to define the type of object in an application. An object is referred as an instance of a class. The objects can be created by using the new keyword following the class name that the object is based on in the code. The code snippet to demonstrate the object creation is as mentioned below:

   Student s1 = new Student();

The instance of the class is created, reference of the object is passed back to the programmer.

The sample code of class is as shown below:

namespace ConsoleApplication1
{
    class Student
    {
        private string name;
        public Student ( string name1 )
        {
            name  = name1;
        }
        public void display()
        {
            Console.WriteLine(“The name is: ”+ name);
        }
         static void Main ( string[ ] args )
        {
            Student s1 = new Student ( “John”);
            s1.display();
            Console.ReadLine ();
        }
    }
}

The output is:

3.3 Main method in C# class

The Main method is where the program starts the execution in C#. It is the entry point of program that executes all the objects and methods in the application. There can be only one method in C# application. The main method can have void or int as the return type. It must be placed inside the class or struct. The static modifier is used for defining the main method.

The main method cannot be called inside from other method or function. No method can initiate main method in C#. It cannot take parameter from any other function. It can take parameters as argument through command line.

The sample code for the Main method is as shown below:

namespace ConsoleApplication2
{
    class Result
    {
        float percent;
        int total, num1, num2;
        public void addvalues()
        {
            Console.WriteLine(“Enter the values”);
            num1 = int.Parse( Console.ReadLine());
            num2 = int.Parse( Console.ReadLine());
        }
        public void Calculate()
        {
            total = num1 + num2;
            percent = total / 2 * 100;
        }
        public void display()
        {
            if ( percent < 35 )
            {
                Console.WriteLine(“The result is fail “);
            }
            if ( percent > 35 && percent < 60)
            {
                Console.WriteLine(“The result is good “);
            }
            if ( percent > 60 )
            {
                Console.WriteLine(“The result is best “);
            }
        }
        static void Main( string[ ] args )
        {
            Result r1= new Result();
            r1.addvalues();
            r1.Calculate();
            r1.display();
            Console.ReadLine();
        }
    }
}

The output is:

3.4 Command Line Input

The parameters can be passed to a Main() method in C# and is called as command line argument. The array of parameters are passed to the Main() method. In the Main() method, args is a string type of array that can contain parameters.

The steps for executing the command line input are as follows:

1) Open Notepad and add the following code

using System;

namespace command
{
    class Program1
    {
        static void Main ( string[ ] args )
        {
            Console.WriteLine(“First Name is”+ args[0] );
            Console.WriteLine(“Last Name is”+ args [1] );
            Console.ReadLine();
        }
    }
}

2) Save the file with the name command.cs

3) Open the Visual Studio command prompt and compile the code as follows:

a) Set the current path to the one with the file saed in the system

b) Compile it with csc command.cs

4) Execute the program using the following command line argument :

command Mark Richard

The output is as shown below:

In the above example, user passed the parameters as Mark Richard to the main method. The Main() method accepts both parameters and holds it to the args variable that is string type array. The values are accessed using the index position.

3.5 Console Input/Output

The Console class allows user to use the Write() and WriteLine() functions to display data on the screen. The Read() method is used to get a value from the user. The syntax for Read() method is as shown below:

     variableName = console.Read();

The value entered by the user is assigned to the corresponding variable on the left side using the assignment variable. The ReadLine() method performs the same functionality as the Read() method but sends a caret to the next line.

The WriteLine() method displays the value on new line in the application. The syntax for WriteLine() method is as shown below:

     string FirstName;
     Console.WriteLine(“Enter the name” );
     FirstName = Console.ReadLine();

 

The sample code is as shown below:

using System;
class Student
{
    static void Main()
    {
        string course;
        string name;
        course = Console.ReadLine();
        name = Console.ReadLine();
        Console.WriteLine(“course is :” + course );
        Console.WriteLine(“Name os { 0} “ +name );
        Console.Read();
    }
}

The output is as shown below:

Like us on Facebook