Learn C# Console in short


What is Program?

A Computer needs a set of instruction called a program to perform any operation. A program needs to be written in a specific language called programming language. So that the computer can understand the instructions. C# is one such programming language.


A compiler is a special program that processes the statements written in a particular programming language and converts them into machine language.

Classes in C#:-

C# Classes are the primary building blocks of the language. C# also provides certain predefined set of classes and methods.


Namespace is a collection of classes.

Class Keyword:-

The class is used to declare a class.

Class Name:-

The class keyword is followed by the name of the class.

The Main() Method:-

The first line of code that a c# compiler looks for in the source file is the Main() method. This method is the entry point for an application. This means that the execution of code starts from the Main() method.  The main method is ideally used to create objects and invoke the methods of various classes that constitute the program.

System.Console.WriteLine() Method:-

Console is a class that belongs to the system namespace. The Console class includes a predefined WriteLine() method. This  method displays the enclosed text on the user’s screen.

Add a namespace” Using System;” at the top of the Program on Visual Studio.
Console.WriteLine(“Welcome to Rahul Sharma’s Blog”);

The dot(.) character  is used to access the methods.


To read the input provided by the user’s  you can use the ReadLine() methods.

Escape Sequences:-

An escape sequence is a combination of characters consisting of a backslash (\) followed by a letter or a combination of digits.



A variable is a location in the memory that has a name and contains the value.

 Naming variable in C#:-

  1. A variable name must begin with a letter or an underscore(‘_’) which may be followed by a sequence of letters, digits(0-9) or underscore. The first character of a variable name cannot be a digit.
  2. A variable name should not contain any embedded spaces or symbols such as ? ! @ + - % etc.
  3. A variable name must be unique.
  4. A variable name can have any number of characters.
  5. Keywords cannot be used as a variable names.

Types of Data Types:-

  1. Value Types
  2. Reference Types
  3. Dynamic Data Type

Value Types:- 

The value types directly contain data. Some examples of value types are char, int, and float which can be used for storing alphabets, integers and floating point values respectively.
Int num;  //variable declared
Num=5; // Memory allocated

Reference Types:- 

 The Reference type variable, instead of containing data, contain a reference(address) to the data stored in the memory.

Dynamic Data Type:- 

 A variable declared with the dynamic data type can be used to store a value of any type. A variable of this data type is declared by using the dynamic keyword.
Dynamic id;

Built In Data Type
Variable Length

Write your First Program in C#:-

Console.ReadLine by default accepts the data in string format, so if you use non string data type then need to convert as per the data type you used.

The Using Keyword:-

 The using keyword is used to include the namespaces in the program.


Keywords are the reserved words that have special meaning.

Comment Entry:-

Comments are used to explain the code in a program. Compilers ignore the comment entry included in a program.
  1.       Single Line Comment.      //
  2.       Multiline Comment.      /*     your code explanation */

Member Variables:-

Data Members of a class are called member variables.

Member Functions:-

Member Methods are also known as member functions.

Instantiating Class:-

Student st =new student(); // create an object of the class. Student is the name of the class.
The new keyword is used to allocate memory to an object at run time.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
    class Program
        // Member variables
        string name;
        dynamic roll_no;

        //Member functions
        public void Input()
            Console.WriteLine("Enter the name of the student");
            name = Console.ReadLine();
            Console.WriteLine("Enter Roll No.");
            roll_no = Console.ReadLine();
        public void output()
            Console.WriteLine("Name={0}", name);
            Console.WriteLine("Roll Number={0}", roll_no);
            Console.BackgroundColor = ConsoleColor.DarkRed;
        static void Main(string[] args)
            Program student = new Program();

Operators and Programming Constructs

Arithmetic Operator


Arithmetic Assignment 


Comparison Operator

Logical Operator

 Conditional Construct

Switch Case Construct

Using Loop Constructs

While Loop

Do While Loop

For Loop

Break and Continue Statements

Working with class Members

Access Specifier:-

An Access specifier defines the scope of a class member. The scope of a class member refers to the portion of the application from where the member can be read and or written to. It is also known as the accessibility of the member.

Types of Access Specifier:-

  1. Public
  2. Private
  3. Protected
  4. Internal
  5. Protected Internal


The public access specifier allows a class to share its member variables and member function with other classes (within or outside the assembly in which the class is defined.


Private access specifier allows a class to hide its member variables and member functions from other classes. There the private members of a class are not visible outside a class.


Protected access specifier allows a class to hide its member variables and member functions from other classes, except those classes that inherit their features from the class.


Default access specifier for the class is internal.
Internal access specifier allows a class to expose its member variables and member functions to other class functions and objects within the assembly in which the member is defined.

Protected Internal:-

Protected internal access specifier allows a class to expose its member variables and member functions to the containing class, child classes or classes within the same assembly. 

Passing Information to Methods:-

You can pass information in and out of a method. This can be done with the help of paramaters.

Declaring Parameterized Methods:-

Calling Parameterized Methods:-

Parameters can be passed by using the following mechanism:-


Parameters passed by using this mechanism are also referred to as input parameters because data can be passed into the method but cannot be returned out of it. This is because any changes to the parameter that occur within the method do not get reflected outside the method.


Parameters passed by using this mechanism are also referred to as input/output parameters because the data can be passed into the method and can also be returned by it. This is because the reference of the parameter is passed to the method instead of passing the actual value. Therefore any changes to the parameter that occur within the method are also reflected outside the method.


 Parameters passed by using this mechanism are also referred to as output parameters because the data can be extracted from the method. Any changes made to the parameter within a method are also reflected outside the method. An output parameter is declared by using the out keyword.

Passing Parameter by value:-

Pass by value is the default mechanism for passing parameters to a method. The value parameter can be defined by specifying a data type followed by a variable name. When a method is called, a new storage location is created for each value parameter.

Output will be 6 not 7.

Passing Parameter by Reference:-

A reference parameter is a reference to the memory location of a parameter. Unlike a value, parameter a reference parameter doesn’t create a new storage location. Instead, a reference parameter represents the same location in memory as the variable that is supplied in the method call.

Output will be 7 not 6.

Passing Parameter by output:-

To return a value from method you can use the return statement. A return statement can be used to return only a single value. This limitation overcome by output parameter because you can pass multiple output parameters to a method.


The process of calling a function from within its body is known as recursion.

The main advantage of recursion is that it is useful in writing clear, short and simple programs.

Using Static Attributes and Static Methods:-

All member variables have a specific lifetime. For example, if you create a integer variable with any name inside the function, the variable will be destroyed when the function execution Completes. In other words every time the function is called, variable will be created, initialized then destroyed when the function exits.

If you want a member variable to retain its value throughout the program, you can declare it as static variable in your program. 

Static Attributes:-

The keyword static means that only one instance of a given variable exists for a class. Static variables are used to define constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition.

Let’s understand static with the help of examples:-
Write a short program using declare variable without static and with static.

 Without Static:-

With Static:-

Static Method:-

In addition to declaring variable as static, you can declare functions as static. Such functions can access only static variables. In a situation where you want to check whether an object of a class has been created, you can make use of static functions because they exist even before the object is created.

Static Method Example:-

Calling Static Method:-

Working with Constructors and Destructors:-

If you want member variables to be initialized as soon as an object is created, you can declare special functions called constructors. You may also need to delete the objects from the memory after they have been used. This can be done in functions called destructors.

Implementing Constructors:-

Constructors are special methods that are automatically invoked on the creation of an object. A constructor need not be called explicitly. Constructors are responsible for object initialization and memory allocation of its class. If we create any class without constructor, the compiler will automatically create one default constructor for that class. There is always at least one constructor in every class.

Here you need to remember that a class can have any number of constructors and constructors don’t have any return type, not even void and within a class we can create only one static constructor.

Constructor name should be same as class name. If we want to create a constructor in a class we need to create a constructor method name same as class name.

Types of Constructors:-

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Static Constructor
  5. Private Constructor

Default Constructor:-

A constructor without having any parameters called default constructor. In this constructor every instance of the class will be initialized without any parameter values.

Parameterized Constructor:-

A constructor with at least one parameter is called as parameterized constructor. In Parameterized constructor we can initialize each instance of the class to different values.

Copy Constructor:-

A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance.
The Constructor which creates an object by copying variables from another object is called a copy constructor.


Static Constructor:-

When a constructor is created as static, it will be invoked only once for all of instances of the class and it is invoked during the creation of the first instance of the class or the first reference to a static member in the class. A static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

Some key points of a static constructor is:
  1. A static constructor does not take access modifiers or have parameters.
  2. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  3. A static constructor cannot be called directly.
  4. The user has no control on when the static constructor is executed in the program.
  5. A typical use of static constructors is when the czlass is using a log file and the constructor is used to write entries to this file.
  6. Only one static constructor will allowed.

Private Constructor:-

When a constructor is created with a private specifier, it is not possible for other classes to derive from this class, neither  possible to create an instance of this class. They are usually used in classes that contain static membersonly. Some key points of a private constructor are:
  1. One use of a private constructor is when we have only static members.
  2. It provides an implementation of a singleton class pattern
  3. Once we provide a constructor that is either private or public or any, the compiler will not add the parameter-less public constructor to the class.

Implementing Destructor:-

Destructors are special methods that are used to release an instance of a class from memory. A class can have only one destructor. The purpose of the destructor is to perform the required memory cleanup action. The Programmer has no control on when to call the destructor.

Since C# is garbage collected, meaning that the framework will free the objects that you no longer use, there may be times where you need to do some manual cleanup. A destructor, a method called once an object is disposed, can be used to cleanup resources used by the object. Destructors doesn't look very much like other methods in C#. Here is an example of a destructor for our Car class:




Garbage Collection 


The Garbage collection is very important technique in the .Net framework to free the unused managed code objects in the memory and free the space to the process.

Garbage Collection in .Net framework

The garbage collection (GC) is new feature in Microsoft .net framework. When we have a class that represents an object in the runtime that allocates a memory space in the heap memory. All the behavior of that objects can be done in the allotted memory in the heap. Once the activities related to that object is get finished then it will be there as unused space in the memory.

The earlier releases of Microsoft products have used a method like once the process of that object get finished then it will be cleared from the memory. For instance Visual Basic, An object get finishes that work then there we have to define a "nothing" to that object. So, it clears the memory space to the processors.

Microsoft was planning to introduce a method that should automate the cleaning of unused memory space in the heap after the life time of that object. Eventually they have introduced a new technique "Garbage collection". It is very important part in the .Net framework. Now it handles this object clear in the memory implicitly. It overcomes the existing explicit unused memory space clearance.

Garbage Collection

The heap memory is divided into number of generations. Normally it is three generations. The Generation 0 is for short live objects, Generation 1 is for medium live objects which are moved from Generation 0. Generation 3 is mostly stable objects.

When an object is created then it will allocate the memory space which will be higher. It will be in the Generation 0 and the memory allocation will be continuous without any space between the generations of garbage collectors.


This property in the GC class returns the total number of generations.  

MaxGeneration property will return the highest generation in the garbage collection. It will be counted as total number of generations in the GC class which starts from 0.Here it has returned 2 as maxGeneration. That means totally three generations in the Garbage Collection. They are Generation 0, Generation 1 and Generation 2. 

How it works

Implicit Garbage Collection should be handled by the .Net framework. When object is created then it will be placed in the Generation 0. The garbage collection uses an algorithm which checks the objects in the generation, the objects life time get over then it will be removed from the memory. The two kinds of objects. One is Live Objects and Dead Objects. The Garbage collection algorithm collects all unused objects that are dead objects in the generation. If the live objects running for long time then based on that life time it will be moved to next generation.

The object cleaning in the generation will not take place exactly after the life time over of the particular objects. It takes own time to implement the sweeping algorithm to free the spaces to the process.

Exception Handling

The Garbage collection has designed such a way that it can be implicitly handling to collect the free spaces in memory. But as I said it takes own time to uses the algorithm to collect unused objects in the memory.

If we want to forces to collect unused objects or explicitly release particular object from the memory. The code allows us to clear the object from the heap immediately.

When it happens

The garbage collector periodically checks the heap memory to reclaim the objects when the object has no valid references in the memory.

When an object is created then it will allocate the memory in the heap then it checks the available space for the newly created objects, if the available space is not adequate to allot the space then it automatically garbage collect the unused objects. If all are valid referenced objects then it gets additional space from the processor.

If the object has reference with managed code objects then it will not free the memory space. However it cannot control the reference with unmanaged code objects, when application forces to collect the unused objects. But it can be achieved to write the explicit coding to avoid managed objects reference with unmanaged objects. 

GetTotalMemory and GetGeneration

Here GetTotalMemory shows the total number of memory occupied by the various resources. Here I have added one more managed code objects in the heap memory. After adding, the size of the memory has increased.

The GetGeneration method will find out the particular managed object in the which generation. Here it shows the Object oBaseGC in the 0th generation. 

C# provides special methods namely

  1. Finalize
  2. Dispose

Which are used to release the instance of a class from memory.


The finalize destructor is a special method that is called from the class to which it belongs or from the derived classes. This destructor is called after the last reference to an object is released from the memory. The .Net Framework automatically runs the finalize destructor to destroy the objects in the memory. However it is important to remember that the Finalize() destructor may not execute immediately when an object loses scope. 

This is because the compiler calls the Finalize() destructor by using a system called reference tracing garbage collection. In reference tracing garbage collection the compiler periodically checks for objects that are not used by the application. When such an object is found, the finalize destructor is called automatically and the garbage collector of compilers releases the object from the memory.


The dispose method is called to release a resource, such as database connection, as soon as the object using such a resource is no longer in use. Unlike finalize destructor the dispose method not called automatically, and you must explicitly called it in your program when an object is no longer needed. The IDisposable interface contains the dispose method. Therefore to call the dispose method, the class must implement the IDisposable interface.

Defining Properties:-

Properties are a natural extension of attributes. They help a class provide a public interface for getting and setting values for private attributes, while hiding the implementation.
A property, generally has a private data member, accompanied by accessor functions and is accessed as a field of a class.

A property is usually declared private in a class and a set of public set and get accessor methods provide access to the property. The get and set methods are like any other method. They can perform any program logic, throw exceptions be overridden, and be declared with any modifier.
A major advantage of properties is that you can run some lines of code at the time of assigning value to a variable, you can use a property. 

In which case we can use Properties:-

Think about it: You have a room and a door to enter this room. If you want to check how who is coming in and secure your room, then you should use properties otherwise they won’t be any door and every one easily come in w/o any regulation.


Creating Value Types and Reference Types

Using Structures:-

A structure is a value type data type. When you want a single variable to hold a related data of various datatypes, you can create a structure. To create a structure you need to use a struct keyword. Structures are used to represent a record.

Characteristics of Structure:-

  1. It logically represents a single value, similar to primitive types (integer, double and so on).
  2. It has an instance size smaller than 16 bytes.
  3. It is immutable (unable to be changed).
  4. It will not have to be boxed frequently.

Using Enumerations:-

Enumeration is a value type data type, which means that enumeration contains its own values and cannot inherit or pass inheritance. Enumerator allows you to assign symbolic names to integral constants. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.

Enums type can be integer (float, int, byte, double etc).But you use beside int it has to be cast.

Some Points about Enum:-

  1. Enums are enumerated data type in C#.
  2. Enums are not for end user, they are meant for developers.
  3. Enums make your code much more readable and understandable.
  4. Enum values are fixed.
  5. Enum can be displayed as a string and processed as an integer.
  6. Every enum type automatically derives from System.Enum and thus we can use System.Enum methods on enums.
  7. Enums are value types and are created on the stack and not on the heap.

Important Thing:-

Stack vs Heap:-

Stack is used for static memory allocation and heap for dynamic memory allocation, both stored in the computer’s RAM. Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and its allocation is dealt with when the program is compiled.

Program showing enum type having same values:-

Program to findout number of values in enum:-


Array is the collection of values of the same data type. An array index starts at zero. That means the first item of an array starts at the 0th position. The position of the last item on an array will total number of items -1. So if an array has 10 items, the last 10th item is at 9th position.

In c# arrays can be declared as fixed length or dynamic.

A fixed length array can store a predefined number of items.

A dynamic array does not have a predefined size. The size of a dynamic array increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined.

Let's take a look at simple declarations of arrays in C#. The following code snippet defines the simplest dynamic array of integer types that does not have a fixed size.
int[] intArray;

As you can see from the above code snippet, the declaration of an array starts with a type of array followed by a square bracket ([]) and name of the array.

The following code snippet declares an array that can store 5 items only starting from index 0 to 4.

int[] intArray;
intArray = new int[5];

The following code snippet declares an array that can store 100 items starting from index 0 to 99.

int[] intArray;
intArray = new int[100];

Defining arrays of different types

In the previous code snippet, we saw how to define a simple array of integer type. Similarly, we can define arrays of any type such as double, character, and string.

In C#, arrays are objects. That means that declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator.

The following code snippet defines arrays of double, char, bool, and string data types.

double[] doubleArray = new double[5];
char[] charArray = new char[5];
bool[] boolArray = new bool[2];
string[] stringArray = new string[10];

Initializing Arrays

Once an array is declared, the next step is to initialize an array. The initialization process of an array includes adding actual data to the array.

The following code snippet creates an array of 3 items and values of these items are added when the array is initialized.

// Initialize a fixed array
int[] staticIntArray = new int[3] {1, 3, 5};

Alternative, we can also add array items one at a time as listed in the following code snippet.

// Initialize a fixed array one item at a time
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;

The following code snippet declares a dynamic array with string values.

// Initialize a dynamic array items during declaration
string[] strArray = new string[] { "Rahul Sharma"“Pankaj""Kashish""Praveen Kumar","Dinesh Beniwal" };

Accessing Arrays

We can access an array item by passing the item index in the array. The following code snippet creates an array of three items and displays those items on the console.

// Initialize a fixed array one item at a time
int[] staticIntArray = new int[3];
staticIntArray[0] = 1;
staticIntArray[1] = 3;
staticIntArray[2] = 5;

// Read array items one by one

This method is useful when you know what item you want to access from an array. If you try to pass an item index greater than the items in array, you will get an error.

Copying an Array:-

When you copy an array to another array, both the source and the target refers to the same array instance in the memory.


If you don’t know the size of the array then you can use foreach loop or you can say that foreach loop removing the need for you to check the array size.

Param Array:-

While declaring a method if you are not sure about the number of arguments to be passed as a parameter, you can use the param array.

In the list of parameters for a method param array should be the last parameter.

Single Dimension Arrays

Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store number of items of a predefined type. All items in a single dimension array are stored contiguously starting from 0 to the size of the array -1.

The following code declares an integer array that can store 3 items. As you can see from the code, first I declare the array using [] bracket and after that I instantiate the array by calling the new operator.

int[] intArray;
intArray = new int[3];

Array declarations in C# are pretty simple. You put array items in curly braces ({}). If an array is not initialized, its items are automatically initialized to the default initial value for the array type if the array is not initialized at the time it is declared.

The following code declares and initializes an array of three items of integer type.
int[] staticIntArray = new int[3] {1, 3, 5};

The following code declares and initializes an array of 5 string items.
string[] strArray = new string[5] { "Mahesh""Mike""Raj""Praveen""Dinesh" };

You can even directly assign these values without using the new operator.

string[] strArray = { "Mahesh""Mike""Raj""Praveen""Dinesh" };

You can initialize a dynamic length array as follows:

string[] strArray = new string[] { "Mahesh""Mike""Raj""Praveen""Dinesh" };

Multidimensional Array:-

The rank value of the array is also known as the dimension of the array. The arrays declared and used in the preceding examples are single dimensional arrays. In a single dimensional array, values are stored in a single row. In addition to single dimensional arrays, you can declare multidimensional arrays, which store data in more than one row.

Array Class:-

The array class is the base class for all the arrays in C#. The array class is defined in the system namespace and provides various properties and methods to work with arrays.

Properties of the arrays class:-

Methods of the array class:-


Indexers are usually known as smart array in c#. They help you to use an object as an array. Indexers are normally used while creating a collection class.

Similar to properties, indexers have a set of setter and getter methods, called accessors.


Points about Indexer

  • Indexer Concept is object act as an array.
  • Indexer an object to be indexed in the same way as an array.
  • Indexer modifier can be private, public, protected or internal.
  • The return type can be any valid C# types.
  • Indexers in C# must have at least one parameter. Else the compiler will generate a compilation error.

Important points to remember on indexers: 
  • Indexers are always created with this keyword.
  • Parameterized property are called indexer.
  • Indexers are implemented through get and set accessors for the [ ] operator.
  • ref and out parameter modifiers are not permitted in indexer.
  • The formal parameter list of an indexer corresponds to that of a method and at least one parameter should be specified.
  • Indexer is an instance member so can't be static but property can be static.
  • Indexers are used on group of elements.
  • Indexer is identified by its signature where as a property is identified it's name.
  • Indexers are accessed using indexes where as properties are accessed by names.
  • Indexer can be overloaded.

Difference between Indexers and Properties:-

Indexers are created with this keyword
Properties don’t require this keyword
Indexers are identified by signature
Properties are identified by their names
Indexers are accessed using indexes
Properties are accessed by their names
Indexer are instance member, so can’t be static
Properties can be static as well as instance members

Using Collections:-

Microsoft has introduced a concept called collections that consists of set of classes that provides array functionality in a superior manner.

Let us consider an example suppose you want to store the name of five employees, by using the following statement.
String[5] =Employees;
Employees = new string[5];
Here the size of the array is fixed to five elements. In addition you have to write code to perform standard operations such as adding elements to the array or sorting the array.
The preceding problem can be avoided using the collection.

A collection is similar to an array. However it has a lot of code wrapped around it to manage the data that it contains. In addition the size of a collection can be expanded as per requirement. In c# collections are implemented by using special classes declared in the System.Collections namespace.

Unlike an array a collection can store data of different data types.

Elements are stored in a collection as objects.  For example when you assign an integer value to an element of a collection, the value is automatically converted to an object and stored in the collection. However, when you try to retrieve a value stored in a collection into a variable, the variable needs to be of the same data type as the value being retrieved, otherwise the program produces an error. This limitation of collections can be overcome by using strongly typed collections, which can be created using the concept of generics.


When you want to access the elements of a array through its index value, you can use an ArrayList class. The use of the arraylist class is an alternative to the use of the array and overcomes the limitations of using an array.

  1. ArrayList is a class that is similar to an array, but it can be used to store values of various types.
  2. An  ArrayList doesn’t have specific size.
  3. Any number of elements can be stored.

ArrayList Functions:- 

ArrayList Example:-


Hashtable is similar to arraylist but represents the items as a combination of a key and value.


Is a class whose object represents the data in a combination of key and value pairs.


  1. Is a class that has the combination of arraylist and hashtable.
  2. Represents the data as a key and value pair.
  3. Arranges all the items in sorted order.




A primary limitation of collections is the absence of effective type checking. This means that you can put any object in a collection because all classes in the c# programming language extend from the object base class. This compromises type safety and contradicts the basic definition of c# as a type safety language.

(Type Safety :- Type safe code accesses only the memory locations it is authorized to access. For example:-  Type safe code cannot read values from another objects private fields. It accesses types only in well defined, allowable ways.)

To address the type safety issue, the .Net framework provides generics to create classes , structures, interfaces and methods that have placeholders for the types they use. Generics are commonly used to create type safe collections for both reference type and value types.
The .Net framework provides an extensive set of interfaces and classes in the System.Collections.Generic namespace for implementing generic collection.

Advantages of Generics:-

  1. Reusability
  2. Type Safety
  3. Performance


You can use a single generic type definition for multiple purposes in the same code without any alterations. For example:- you can create a generic method to add two numbers. This method can be used to add two integers as well as two floats without any modification in the code.

Type Safety:-

Generic data type provide better type safety, especially in the case of collections. When use generics you need to define the type of objects to be passed to a collection. This helps the compiler to ensure that only those object types that are defined in the definition can be passes to the collection.


Generic types provides better performance as compared to normal system types because they reduce the need for boxing, unboxing and type casting of variables or objects.

Extending Existing Classes

Defining Inheritance:-

One of the most powerful characteristics of the object oriented approach is code reuse.
Inheritance is a process of deriving new classes from existing classes. The existing class is called the base class or super class and the inherited class is called the derived class or sub class.

The derived classes contain all the attributes and behaviors of the existing classes, plus their own attributes and behaviors.

class shape
        public double width;
        public double height;

        public void showdim()
            Console.WriteLine("Width and Height are" + width + "and" + height);
    class Triangle:shape
        public string style;

        public double Area()
            return width * height / 2;
        public void showstyle()
            Console.WriteLine("Style of triangle is" + style);
    class Program
        static void Main(string[] args)
            Triangle t1 = new Triangle();
            Triangle t2 = new Triangle();
            t1.width = 10;
            t1.height = 20;
            t1.style = "isosceles";
            t2.width = 15;
            t2.height = 20;
            t2.style = "right";

Types Of Inheritance:-

Single Inheritance:-

It is the type of inheritance in which there is one base class and one Derived Class.

Hierarchical Inheritance:-

This is the type of inheritance in which there are multiple classes derived from one base class. This type of inheritance is used when there is a requirement of one class feature that is needed in multiple classes.

Multilevel Inheritance:-

When a sub class is derived from the derived class, the mechanism is known as multilevel inheritance.

Abstract Classes and Methods:-

An abstract class is a class that is incomplete and cannot be used directly. Abstract classes contains abstract methods, which can be implemented by the derived classes. You cannot create an instance of an abstract class to use its member functions. However you can override the methods of the abstract class in the derived class and provide a new functionality to them.

Abstract methods are methods without any body. The implementation of an abstract method is done by the derived class. When a derived class inherits an abstract method from an abstract class, it must override the abstract method to provide it a new functionality.

There are certain rules governing the use of an abstract class:-

You cannot create an instance of an abstract class.
You cannot declare an abstract method outside the abstract class.
A class, which is derived from an abstract class, must override all the methods of the abstract class.
An abstract class is defined by using the abstract keyword before the class keyword.

Virtual Functions:-

When you want to provide a different implementation to a function in a sub class than the one defined in the super class you need to define a function as virtual in the super class. Virtual functions do not make overriding compulsory, as in case of abstract functions, but give the choice to the user. The functionality of the virtual function can be modified by the inherited class according to requirement.

To declare a virtual function, the virtual keyword is used before the return type of the function and after the access modifier of the function.

class Animal
        public virtual void Foodhabit()
            Console.WriteLine("Different food habbit");
    class carnivorous:Animal
        public override void Foodhabit()
            Console.WriteLine("Eat Meat");
    class herbivorous:Animal
        public override void Foodhabit()
            Console.WriteLine("Eat Plants");
    class Implement
        public void callfunction(Animal an)
    class Program
        static void Main(string[] args)
            Implement imp = new Implement();
            carnivorous cn = new carnivorous();
            herbivorous hb = new herbivorous();

Early Binding vs Late Binding:-

The mechanism of linking a function with an object at run time is called late binding. It is also known as dynamic binding. On the other hand, the mechanism of linking a function with an object at compile time is called early binding. It is also known as static binding.

Sealed Class:-

There may be times when you do not need a class to be extended. You may even want to force users not to inherit a class. You could restrict users from inheriting the class by sealing the class using the sealed keyword. The keyword tells the compiler that the class is sealed, and therefore, cannot be extended. No class can be derived from sealed class.

An interface looks like a class, but has no implementation. The only thing it contains are declarations of events, indexers, methods and properties. The reason interfaces only provide declarations is because they are inherited by structs and classes, that must provide an implementation for each interface member declared.

Add a Interface Class using right click on project name on Solution Explorer.

namespace Interface
  public  interface Ione
        void one();
  public  interface Itwo
        void two();
  public  interface Ithree:Ione
        void three();
  public  interface Ifour
        void four();
  public  interface Ifive:Ithree
        void five();
  public  interface Ieven: Itwo,Ifour

  public  class OddEven : Ieven,Ifive
        public void one()
            Console.WriteLine("This is one");

    public void Two()
        public void Three()
            Console.WriteLine("THis is Three");
        public void Four()
            Console.WriteLine("This is Four");
        public void Five()
            Console.WriteLine("THis is Five");

        void Ifive.five()
            //throw new NotImplementedException();

        void Ithree.three()
           // throw new NotImplementedException();

        void Ione.one()
            //throw new NotImplementedException();

        void Itwo.two()
           // throw new NotImplementedException();

        void Ifour.four()
            //throw new NotImplementedException();


namespace Interface
    class Program
    static void Main(string[] args)
            Console.WriteLine("Odd Numbers");
            Ifive oe = new OddEven();
            Console.WriteLine("Even Number");
            Ieven oe1 = new OddEven();

Implementing Polymorphism


 The term polymorphism was derived from the Greek words Poly (means many) and morphs (meaning forms). Polymorphism is the ability to allow a function to exist in different forms. For example:- A person can react differently to various situations. Therefore, different moods of a person, depending upon the situation he is in, depict polymorphism.
Techniques to Implement polymorphism:-

1>  Method overloading
2>  Operator Overloading
3>  Method Overriding

Method/Function Overloading:-

Method overloading allows you to assign same name to two methods that perform similar function, but take different number or type of parameters.


   class getmax
        public int max(int num1, int num2)
                return num1;
                return num2;
        public float max(float num1,float num2)
                return num1;
                return num2;
    class Program
        static void Main(string[] args)
            getmax gm = new getmax();
            Console.WriteLine(gm.max(5, 6));
            Console.WriteLine(gm.max(4.5f, 5.6f));

Constructor Overloading:-

Constructors are special types of methods, and therefore, they can also be overloaded. Overloaded constructors are commonly used in C# to provide flexibility while creating an object.


class getcalculation
        private int n1, n2, total;
        public getcalculation()
            n1 = n2 = total = 0;
        public getcalculation(int num1,int num2)
            n1 = num1;
            n2 = num2;
            total = 0;
        public void Addnumber()
            total = n1 + n2;
        public void Display()
            Console.WriteLine("Sum of number is" + total);
    class Program
        static int Main(string[] args)
            getcalculation gt = new getcalculation();
            getcalculation gt1 = new getcalculation(5,10);
            return 0;

No comments:

Post a Comment

Insert, Update, Delete Data in Grid View Using Asp Panel on a single form Database:- create table StudentDetails ( Id int i...