Thursday, December 16, 2010

C# Tutorial 1: Basic C#.net concepts

  BASIC CONCEPTS OF C# CONSOLE APPLICATION:

               In this tutorial I will explain all basic conepts of C#.net.  For each and every concept I provided syntax with one sample program.  The contents of this tutorial is as follows::::::::::::::

CONTENTS
1.     .NET VERSIONS
2.     EXTENSION FILES
3.     DATA TYPES
4.     KINDS OF DATA(VALUE TYPE, REFERENCE TYPE)
5.     CONTROL STATEMENTS
6.     CONSOLE APPLICATIONS
7.     ARRAYS
8.     STRUCTURE
9.     PROPERTIES
10.                         GARBAGE COLLECTION
11.                         CALL BY VALUE AND REFERENCE
12.                         INHERITANCE

First I would like to start with versions of .net

.net versions
 There are several versions in .net they are:
Version number    Name of the version
1.1                                 ms.net 2003
2.0                               ms.net2005
3.0                               It is failure
3.5                               ms.net 2008
4.0                                ms.net 2010

Extension of files
   There are three extension files available in  dotnet.  They are as follows:::

  1. solution       .sln
  2. project          .csproj
  3. classes            .cs


Data types
  The following are the data types used in C# and VB.Net

category                    class name                description              vb.net        c#
integer                         byte                             1 byte unsigned int     byte                 byte
                        --          sbyte                            1 byte signed int         byte                 sbyte
                                    int16                            2 byte unsigned int     short                short
                                    int32                            4 byte signed int         integer             int
                                    int64                            8 byte signed int         long                 long
                        --          unit 16                         2 byte unsigned int     ushort              ushort
                        --          unit 32                         4 byte unsigned int     uinteger           uint
                        --          unit 16                         8 byte unsigned int     ulong               ulong
Float                            single                           4 byte floating point   single              float
                                    double                         8 byte floating point   double                        double
                                    decimal                        16 byte floating point decimal       decimal
string                           char                             unicodechardata          char                 char
                                    string                           strings                          string               string
date and time              datetime                      8 byte                           datetime    datetime
                                    timespan                      8bytes                          timespan   timespan
other                            Boolean                       true/false                     Boolean       bool
                        --          intptr                           singleintegers              intptr               intptr
                        --          uintptr                         unsignedinteger           uintptr             uintptr
                                    Object                         any type of daa           object              object






Kinds of data type

  1. Value type—This kind of variables are stored in stack
  2. Reference type—This kind of  values are stored in heap and references in stack
For Example:-,string and object,class,interface,delegate



Control statements
The following are different control statements that can be used in c#
  1. Conditional control statements
  2. Looping control statements

Let us discuss about the above 2 control statements:

  1. Conditional control statements
Under conditional control statements there are again 4 types are there they are:

  1. IF  : Syntax for if condition is as follows:

            If(condition)
            {
                        ---
                        ---
            }
            Else
            {
                        ----
                        ----
            }
  1. IF-Else if : syntax for if else is block is as follows:

If(condition)
            {
                        ---
                        ---
            }
            Else if (condition)
            {
                        ----
                        ----
            }
         Else If(condition)
            {
                        ---
                        ---
            }
            Else
            {
                        ----
                        ----
            }


  1. SWITCH :  switch statement syntax is as follows:

Switch(expression)
{
            Case    Result:
            ---
            ----
            Break;
            ----
            ----
            ----
Default:
            ----
            ----
            Break;
}
  1. Ternary operator(? :)

(condition) ? statement : statement;

  1. Looping control statements: Under this category again there are 4 types. They are as follows:

1.      While
   Syntax for while statement is as follows:
While(condition)
{
      -------
      ------
}
2.      For
   Syntax for creating “For” statement is as follows
For( var initialization;condition;increment/decrement)
{
      -----
      -----
}

3.      Foreach  : syntax for “ForEach” statement is as follows:
For each(datatype var in collection)
{
            ----
            -----
}


4.      Do-while : syntax is as follows:

Do
{
      ----
      ----
} while(condition);


Console application

It is an application that runs  in a dos based console window. To work with Console Application, we have to use a class with name “console” available within the namespace “system”. Console class provides the following methods and properties.
Properties and methods:
1. Background color: used to change the back ground color of console window.
Command:::::::::::::::::::

Console.backgroungcolor=consolecolor.blue

2. fore ground color:
            Used to change the  foreground color of console window.
Command::::::::::::
 Console: Foreground color=concolecolor.red 
3.cusor left:
Used to specify the position of the cursor from left edge of the console window
Command::::::::

Console.cursorleft=50
4. cursor top:
Used to specify the position of the cursor from top edge of the console window

Console.cursortop=60
5. clear()

Used to clear the console window
Console.clear();

Note: all of the above the first 4 will be on .net 2005 but not in old versions.they are properties and remaining are methods.

Methods:
  1. Read(): used to read a single character    var=console.read()
  2. read line():used to read a line of text.used to read other types of data like integer and float    var=console.readline()
  3. write():used to write a data     console.write(“message”)
  4. writeline():used to write a data to the console window but after writing the data the cursor will be taken to next line    console.writeline(“message”)



ARRAYS

Arrays is collection of same data type---
  1. one dimentional array:

datatype[] array name= new datatype[size];
ex., in[] a=new int[5];
  1. dynamic arrays

int []a;
size=5;
a=new int[size];

program:
sun of array
for(int i=0;i<size;s++)
{s=s+a[i];
}:
Multi dimentional array:

Int[,]a;
A=new int[3,3];

Structure:
User defined type that can store more than one value of dissimilar data type

[accessmodifier] struct structure name
{-----------
}
Note:

  1. structure is value type
  2. difference between  structure and class is struct is value type and class is ref type


Properties

A property can be characterized as an object-oriented field. Properties promote encapsulation by
allowing a class or struct to control access to its data and by hiding the internal representation of
the data.
A property is a member that provides access to a characteristic of an object or a class. Examples of
properties include the length of a string, the size of a font, the caption of a window, the name of a customer, and so on.
*********It provides access to private fields of the class


In general it is public

[access modifers] data type property name
{
            Get{}—return a value from the fields
            Set{}—invoked automatically when value assigned to property by implicit object  “value”

}

Program name:

using System;
using System.Collections.Generic;
using System.Text;

namespace properties
{
    class accoutholderdetailts
    {
        int accno;
        string accholdername;
        float balance;
        string acctype;

        public string _Acctype
        {
            get { return acctype; }
            set { acctype = value; }
        }
        //constructor for reading valiues
        public accoutholderdetailts()
        {
            Console.WriteLine("enter account number");
            accno = int.Parse(Console.ReadLine());
            Console.WriteLine("enter account holder name");
            accholdername = Console.ReadLine();
            Console.WriteLine("enter account type(current/savings)name");
            acctype =Console.ReadLine();
            Console.WriteLine("enter account balance");
            balance = int.Parse (Console.ReadLine());
                      
   
       }
        public int _accno
        {
            set
            {
                accno = _accno;
            }
            get
            {
                return accno;
            }
        }
        public string _accholdername
        {
            set
            {
                accholdername = _accholdername;
            }
            get
            {
                return accholdername;
            }
        }
        public float _balance
        {
            set
            {
                balance = _balance;
            }
            get
            {
                return balance;
            }
        }
       
        public void display()
        {
            Console.WriteLine("accno{0}\n  accname {1}\n  acctype {2}\n  balance {3}\n",accno,accholdername,acctype,balance);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            accoutholderdetailts acc = new accoutholderdetailts();
            acc.display();
            Console.Read();
           
        }
    }
}

PROGRAM 2:  Marksproperties

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace marksproperties
{
    class Marks
    {
        int _c, _cpp, _dotnet, _total;
        float _avg;
        string _grade;

               public int c
        {
            get
            {
                return _c;
            }

            set
            {
                if (value > 100)
                {
                    Console.WriteLine("value must be <=100");

                }
                else
                {
                    _c = value;
                }

            }
        }
        public int cpp
        {
            get
            {
                return _cpp;
            }

            set
            {
                if (value > 100)
                {
                    Console.WriteLine("value must be <=100");
                   

                }
                else
                {
                    _cpp = value;
                }

            }
        }
        public int dotnet
        {
            get
            {
                return _dotnet;
            }

            set
            {
                if (value > 100)
                {
                    Console.WriteLine("value must be <=100");

                }
                else
                {
                    _dotnet = value;
                }

            }
        }

        //the following 3 are readonly properties

        public int total
        {
            get
            {
                return _total;
            }
        }
        public float avg
        {
            get {
                return _avg;
            }
        }
        public string grade
        {
            get
            {
                return _grade;
            }
        }
        public void calculate()
        {
            _total = _c + _cpp + _dotnet;
            _avg = _total / 3.0f;
            //f is not mentionsed then compilation eror occurs
            if (_c < 35 || _cpp < 35 || _dotnet < 35)
            {
                _grade = "fail";
            }
            else
            {
                if (avg >= 80)
                {
                    _grade = "distinction";
                }
                else if (avg >= 60)
                {
                    _grade = "first";
               
                }
                else if (avg >= 50)
                {
                    _grade = "second";
                }
                else
                {
                    _grade = "third";
                }
            }
        }
    }
    class Program
    {

            static void Main(string[] args)
        {
                Marks m = new Marks();
               
                Console.WriteLine("enter marks");
                m.c=int.Parse(Console.ReadLine());
                 m.cpp=int.Parse(Console.ReadLine());
                 m.dotnet=int.Parse(Console.ReadLine());
                 m.calculate();
                 Console.WriteLine("total is {0}", m.total);
                 Console.WriteLine("average is {0}", m.avg);
                 Console.WriteLine("grade is {0}", m.grade);
                 Console.ReadLine();
        }
    }
}

Garbage collector in dot net

ü  GC is a component available in clr of .net framework. This is responsible for memory mgt and destroying the objects.
ü  When the gc was invoked the following steps will be performed:
1. When the object is created, memory is allocated for it, the constructor is run, and the object is
considered live.
2. If the object, or any part of it, cannot be accessed by any possible continuation of execution, other than the running of destructors, the object is considered no longer in use, and it becomes eligible for destruction.
3. Once the object is eligible for destruction, at some unspecified later time the destructor (§17.12) (if any) for the object is run. Unless overridden by explicit calls, the destructor for the object is run once only.
4. Once the destructor for an object is run, if that object, or any part of it, cannot be accessed by any
possible continuation of execution, including the running of destructors, the object is considered
 inaccessible and the object becomes eligible for collection.
5. Finally, at some time after the object becomes eligible for collection, the garbage collector frees the
 memory associated with that object.
The garbage collector maintains information about object usage, and uses this information to make memory management decisions, such as where in memory to locate a newly created object, when to relocate an  object, and when an object is no longer in use or inaccessible.

The behavior of the garbage collector can be controlled, to some degree, via static methods on the class System.GC





Call by value and call by reference:

I n  “call by value” The original values cannot be changed

The Original values changed in “call by reference”

In oout keyword also the values will be changed but the place of decalring variables and variable initialization changes in Reference—“out”  keyword and “ref “ keyword

While a refmodifier requires that a variable be assigned a value before being passed to a method, the outmodifier requires that a variable be assigned a value before returning from a method:

Program names:
1.        Callbyvalue

using System;
using System.Collections.Generic;
using System.Text;

namespace call_by_value
{
    class refoutparameters
  {
        int a, b;
        public void show(int p, int q)
        {
            a = p;
            b = q;
            a = 30;
            b = 20;
            Console.WriteLine("u r in call by value function");
            Console.WriteLine("a{0},b{1}", a, b);

        }
   
    }

    class Program
    {
        static void Main(string[] args)
        {
            refoutparameters refobj = new refoutparameters();
            int a = 100;
            int b = 200;
            refobj.show(a, b);

            Console.WriteLine("a {0} and {1}values after call by value", a, b);
            Console.Read();
        }
    }
}

2.        Callbyreference   ref keyword

using System;
using System.Collections.Generic;
using System.Text;

namespace call_by_reference
{
    class exampleforrefkeyword
    {
        public void swap(ref int a, ref int b)
        {
            int temp = a;
            a = b;
            b = temp;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            exampleforrefkeyword ex = new exampleforrefkeyword();
            int a = 100;
            int b = 200;
            Console.WriteLine("before swap a{0}  b{1}", a, b);
            ex.swap(ref a, ref b);
            Console.WriteLine("after swap a{0}  b{1}", a, b);
            Console.Read();
        }
    }
}

3.        Outkeyword
using System;
using System.Collections.Generic;
using System.Text;

namespace outreferenceparameter
{
    class outparameters
    {
        public void getvalue(out int a, out int b)
        {
            a = 10;
            b = 20;
            int temp = a;//here we must intialize values in out reference
            a = b;
            b = temp;

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            outparameters obj = new outparameters();
            int p,q;
            obj.getvalue(out p, out q);
            Console.WriteLine("value of p{0}, q {1}", p, q);
            Console.Read();
        }
    }
}



Inheritance

A class inherits the members of  its direct base class. Inheritance means that a class implicitly contains all members of its direct base class. Advantage is reusability of a class

Types of inheritance
1.       Single Inheritance: In single inheriatance baseclass in inherited to derived calss.
Example:

 

  1. Multiple Inheritance:  Dot net does not support multiple inheritance. Actual multiple inheritance look like  :


  1. Multilevel Inheritance:This multilevel inheritance diagram is as follows:






  1. Heirarchial Inheritance:  Diagram for heirarchial inheritance is as follows:




  1. Hybrid Inheritance :  It is combination of single multi level and heirarchial inheritance. It look like:


 program names:
  1. Single

using System;
using System.Collections.Generic;
using System.Text;

namespace single
{
    class baseclass
    {
        int a, b;
        public void readab()
        {
            Console.WriteLine("enter value of a and b");
            a = int.Parse(Console.ReadLine());
            b = int.Parse(Console.ReadLine());

        }
        public void printab()
        {
            Console.WriteLine("a={0},b={1}", a, b);
        }
    }
    class Derived:baseclass
    {
        int c;
        public void read()
        {
            base.readab();
            Console.WriteLine("enter value of c");
            c = int.Parse(Console.ReadLine());
        }
        public void print()
        {
            base.printab();
            Console.WriteLine("value of c is {0}", c);
        }
        static void Main(string[] args)
        {
            Derived dervobj = new Derived();
            dervobj.read();
            dervobj.print();
            Console.ReadLine();
        }
    }
}


-          - - - - -
[or]     another example for single inheritance-------------
-          -               -               -               -              


using System;
using System.Collections.Generic;
using System.Text;

namespace singleinheritance
{
    class Baseclass
    {
        int a, b;
        public void readab()
        {
            Console.WriteLine("enter value of a:");
            a = int.Parse(Console.ReadLine());
            Console.WriteLine("enter value of b:");
            b = int.Parse(Console.ReadLine());

        }
        public void printab()
        {
            Console.WriteLine("a={0} and b={01}", a, b);
        }
    }
    class derived:Baseclass
    {
        int c;
        public void read()
        {
            //base is the keyword for accessing the base class variables
          
          base.readab();
            Console.WriteLine("enter value sof c");
            c=int.Parse(Console.ReadLine());
        }
        public void printc()
        {
            base.printab();
            Console.WriteLine("c=={0}",c);
        }
    }
    class Program
    {
   
        static void Main(string[] args)
        {
            derived derobj = new derived();
            Console.WriteLine("this is after object going to drived class");
            derobj.read();
            Console.WriteLine("this is after read funtion in main");
            derobj.printc();
            Console.Read();
        }
    }
}


2.       Multi level inheritance program

using System;
using System.Collections.Generic;
using System.Text;

namespace multilevel
{
    class student
    {
        protected int sno;
        protected string sname;
    }
    class marks : student
    {
        protected float eng, maths, science;

    }

    class Program : marks
    {
        public void showmarks()
        {
            sno = 12;
            sname = "nandu";
            eng = 90;
            maths = 80;
            science = 79;
            Console.WriteLine("{0},{1},{2},{3},{4}",sno, sname, eng, maths, science);
            Console.ReadLine();
        }

        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.showmarks();
            Console.WriteLine();
        }
    }
}


  1. Another sample student inheritance program:

using System;
using System.Collections.Generic;
using System.Text;

namespace stuinheritance
{
    class student
    {
        protected int sno, s1, s2, s3;
        protected float avg, tot;
        protected string sname;
        student()
        {
            Console.WriteLine("enter student deails");
            Console.WriteLine("student name");
            sname = Console.ReadLine();
            Console.WriteLine("student no");
            sno = int.Parse(Console.ReadLine());
            Console.WriteLine("student marks");
            s1 = int.Parse(Console.ReadLine());
            Console.WriteLine("student s2");
            s2 = int.Parse(Console.ReadLi bne());
            Console.WriteLine("student name");
            sname = int.Parse(Console.ReadLine());
        }
    }

    class marks : student
    {
   
    }

    class display : student
    {
   
    }
    class Program
    {
    //    protected sno,s1;
   
        static void Main(string[] args)
        {
        }
    }
}

------------~~~~~~~~~~~-----------!!!!!!!!!!!!-------------~~~~~~~~~~~~~~~       
Article by:
N.Nandana,Assistant professor,Tirupati  dated:December 16, 2010.

1 comment:

  1. very nice and useful article......... thanks

    ReplyDelete