Introduction to OOP in C#

Object Oriented Programming (OOP) is a very important part of any language.

Now, here is some information about OOP.

CLASS

  • A class is one type of grouping of objects.
  • A class is a user-defined data type. A class must have a name.
  • A class name is one word. For example Employee, Client, Car and so on and the first letter will be in upper case.
  • A class file is saved with the .cs extension in C#.
  • A class is a very important part of OOP. We see many types of classes in the preceding in this article.
  • A class is declared with the class keyword.

Example

  1. namespace OPPS  
  2. {  
  3.    class OppsDemo  
  4.    {  
  5.       static void Main(string[] args)  
  6.       {  
  7.          // declare variable, method   
  8.       }  
  9.    }  
  10. }  
Object

Objects are used in classes. In this declare a variable and it refers to creating an object or creating an instances of the class.

A variable is declared with the var keyword.

Here is one example:
  1. class OppsDemo  
  2. {  
  3.    static void Main(string[] args)  
  4.    {  
  5.       Demo d = new Demo();  
  6.   
  7.    }  
  8. }  
Note: The created class is available in any current project.

Also create a null object inside a class.
  1. Demo d = null;  
In this, see the new keyword is for garbage collection. In other words, when we declare using the new keyword you create space for the new variable. Garbage Collection will automatically clean up the value in the .NET Framework.

Now we declare a variable in the Employee class as in the following:
  1. class Employee  
  2. {  
  3.    static void Main(string[] args)  
  4.    {  
  5.   
  6.       string Name;  
  7.       int Age;  
  8.    }  
  9. }  
Here for one class example as in the following:

Class Example

Output

Class Example output

Method

A method is one type code block with bracket { }. A method name display is unique because it's use in programmed. A program causes the statements to be executed by calling the method and specifying any required method arguments. A program causes the statements to be executed by calling the method and specifying any required method arguments. Also Pass arguments with method.

Method name declare in one word and first letter be Uppercase because method is one type action. It's a case sensitive.
  1. void Display()  
  2. {  
  3.   
  4. }  
Also in this, Access modifier concept use and make it public, private or internal.

Now we are see one calling method example, 
  1. namespace OPPS  
  2. {  
  3.     public class Addition  
  4.     {  
  5.        public int count(int a, int b)  
  6.        {  
  7.            int c;  
  8.   
  9.            c = a + b;  
  10.   
  11.            return c;  
  12.        }  
  13.        static void Main(string[] args)  
  14.         {  
  15.             int a = 10;  
  16.             int b = 5;  
  17.             int Result;  
  18.   
  19.             Addition add = new Addition();  
  20.            //call method  
  21.             Result = add.count(a, b);  
  22.             Console.WriteLine("Addition Count:{0}",Result);  
  23.             Console.ReadLine();  
  24.              
  25.         }  
  26.     }  
  27. }  
Method

Output:

method output

Now getting some information about Method type,

 

  1. Pass by Value
  2. Pass by References

1. Pass by Value

Now work with pass by value in method. This article provide basic example how to pass value with method.

In this method any value pass as parameter. Here given example:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     public class PersonInfo  
  9.     {  
  10.        private void Info (string Name, string city)  
  11.        {  
  12.            Console.WriteLine("Person Information:");  
  13.            Console.WriteLine("------------------------------------");  
  14.            Console.WriteLine("Person Name:");  
  15.            Console.WriteLine(Name);  
  16.            Console.WriteLine("------------------------------------");  
  17.            Console.WriteLine("Person City:");  
  18.            Console.WriteLine(city);  
  19.        }  
  20.        static void Main(string[] args)  
  21.         {  
  22.             PersonInfo P_Info = new PersonInfo();  
  23.   
  24.             string Name = "Rakesh Chavda";  
  25.             string city = "Ahmedabad";  
  26.   
  27.             P_Info.Info(Name, city);  
  28.              
  29.            Console.ReadLine();  
  30.              
  31.         }  
  32.     }  
  33. }  
Pass by Value

Output:

Pass by Value Output


In this example see two type static method. One is entry point in application and other method is Info, it's pass two parameter name and city and display.

Passing value. in this method value store and after display.

2. Pass by References

In this method passing any variable pass by reference.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     class Info  
  9.     {  
  10.         public string Name;  
  11.         public string city;  
  12.     }  
  13.   
  14.     public class PersonInfo  
  15.     {  
  16.         static void Main(string[] args)  
  17.         {  
  18.             Info i = new Info();  
  19.   
  20.             i.Name = "Rakesh";  
  21.             i.city = "Ahmedabad";  
  22.   
  23.             Console.WriteLine("Person Name: {0}",i.Name);  
  24.             Console.WriteLine("Person City: {0}",i.city);  
  25.              
  26.            Console.ReadLine();  
  27.              
  28.         }  
  29.     }  
  30. }  
Pass by References

Output:

Pass by References output


Here see class info string value declare as public. In side method declare object info and assign the both string value.

In this also reference value assign with ref keyword. Here give example,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     public class PersonInfo  
  9.     {  
  10.   
  11.         static void PersonAge1(ref int age) // 1st Person  
  12.         {  
  13.             age = 25;  
  14.         }  
  15.         static void PersonAge2(ref int age) // 2nd Person  
  16.         {  
  17.             age = 28;  
  18.         }  
  19.         static void Main(string[] args)  
  20.         {  
  21.             int age = 0;  
  22.   
  23.             PersonAge1(ref age);  
  24.             Console.WriteLine("1st Person Age : {0} ",age);  
  25.   
  26.             PersonAge2(ref age);  
  27.             Console.WriteLine("2st Person Age : {0} ",age);  
  28.   
  29.            Console.ReadLine();  
  30.              
  31.         }  
  32.           
  33.     }  
  34. }  
program

Output

program output

Pass by Out reference

In this also the reference value is assigned with the out keyword. Here, see in this example, the difference between ref and out.

Both check on the programmed compile time with the ref and out keyword values. In this the out reference is necessary given any type set output in a program. And with the ref assigning an output value or not it passes a parameter.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     public class PersonInfo  
  9.     {  
  10.   
  11.         static void PersonAge1(ref int age) // 1st Person with ref   
  12.         {  
  13.              
  14.         }  
  15.         static void PersonAge2(out int age) // 2nd Person with out  
  16.         {  
  17.             age = 28;  
  18.         }  
  19.         static void Main(string[] args)  
  20.         {  
  21.             int age = 0;  
  22.   
  23.             PersonAge1(ref age);  
  24.             Console.WriteLine("1st Person Age : {0} ",age);  
  25.   
  26.             PersonAge2(out age);  
  27.             Console.WriteLine("2nd Person Age : {0} ",age);  
  28.   
  29.            Console.ReadLine();  
  30.              
  31.         }  
  32.           
  33.     }  
  34. }  
Pass by Out reference

Output

Pass by Out reference output

It does not declare a value ref type so it is given a 0 value for the output.

But if it does not declare a value out type it is given an error at compile time.

That's in both the main and is different at the compiler level.

Encapsulation

Encapsulation is a type access modifier. Encapsulation is for accessing and the visibility of a class member. Here is the csharp supported access specifiers list. 
  1. Public
  2. Private
  3. Protected
  4. Internal
  5. Protected Internal

Encapsulation is the main concept of data hiding or information hiding with the above list access modifier keywords. So, encapsulation is also known as data hiding. An access modifier keyword is set to the accessibility of the class, method, member funcation or member variable.

Now, we are getting some information about the access keyword one by one.

Public

The public access modifier keyword is a class variable or function that can be accessed by any other object or function. That us, any public member van be used from outside the class.

Example

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     public class PublicDemo  
  9.     {  
  10.         class Maths  
  11.         {  
  12.             // declare variable   
  13.             public int a;  
  14.             public int b;  
  15.   
  16.             public int GetValue()  
  17.             {  
  18.                 return a + b;  
  19.             }  
  20.             public void ShowResult()  
  21.             {  
  22.                 Console.WriteLine("Value of A: {0}",a);  
  23.                 Console.WriteLine("Value of B: {0}", b);  
  24.                 Console.WriteLine("Result = {0}",GetValue());  
  25.                 Console.ReadLine();  
  26.             }  
  27.         }  
  28.         static void Main(string[] args)  
  29.         {  
  30.             Maths m = new Maths();  
  31.             m.a = 5;  
  32.             m.b = 2;  
  33.             m.ShowResult();  
  34.             Console.ReadLine();  
  35.         }  
  36.      }  
  37. }  
public Encapsulation

Output

public Encapsulation output

Here see, the a and b variables are declared as public and it's accessed with the Maths class as m. Also created the function GetValue() and ShowResult() access variables.

Private

In this access modifier a class variable and a function can be hidden from any other object and function. It is only accessed from the same class, not another; it's private.

Example
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     public class PublicDemo  
  9.     {  
  10.         class Maths  
  11.         {  
  12.             // declare variable   
  13.             private int a;  
  14.             private int b;  
  15.   
  16.             public void InsertValue()  
  17.             {  
  18.                 Console.WriteLine("Enter value of A:");  
  19.                 a = Convert.ToInt32(Console.ReadLine());  
  20.                 Console.WriteLine("Enter value of B:");  
  21.                 b = Convert.ToInt32(Console.ReadLine());  
  22.             }  
  23.             public int GetValue()  
  24.             {  
  25.                 return a + b;  
  26.             }  
  27.             public void ShowResult()  
  28.             {  
  29.                 Console.WriteLine("=============================");  
  30.                 Console.WriteLine("Value of A: {0}",a);  
  31.                 Console.WriteLine("Value of B: {0}", b);  
  32.                 Console.WriteLine("Result = {0}",GetValue());  
  33.             }  
  34.         }  
  35.         static void Main(string[] args)  
  36.         {  
  37.             Maths m = new Maths();  
  38.             m.InsertValue();  
  39.             m.ShowResult();  
  40.             Console.ReadLine();  
  41.         }  
  42.      }  
  43. }  
Output

Private


In this example a and b are declared as private so here the InsertValue() and GetValue() functions are created to access it.

Protected

The protected access specifier allows a class to hide its member variables and member functions from other class objects and functions, except child classes.

Example
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     public class MathsDemo  
  9.     {  
  10.         class Maths1  
  11.         {  
  12.             public int R;  
  13.             protected int J;  
  14.         }  
  15.         class Maths2 : Maths1  
  16.         {  
  17.             public int AddValue()  
  18.             {  
  19.                 R = 5;  
  20.                 J = 29;  
  21.                 return R + J;  
  22.             }  
  23.         }  
  24.         static void Main(string[] args)  
  25.         {  
  26.             Maths2 m2 = new Maths2();  
  27.             m2.R = 5;  
  28.             m2.J = 29;  //--------------------- Error -------------  
  29.             Console.WriteLine(m2.AddValue());  
  30.             Console.ReadLine();  
  31.         }  
  32.      }  
  33. }  
In the preceding example, see it does not call the object of the class Maths1, but inherits the class Maths1 to Maths2. Here given the error line because J is declared as protected, so the protected member cannot access outside the child class but only access inside the child class.

Internal

The internal access specifier allows a class to expose its member variables and member functions to other functions and objects. It can be accessed from any class or method defined with the application in which the member is defined. The default access specifier is internal for a class.

Example
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     public class InternalDemo  
  9.     {  
  10.         class Result  
  11.         {  
  12.             internal int a;  
  13.             internal int b;  
  14.   
  15.             int Addition()  
  16.             {  
  17.                 return a + b;  
  18.             }  
  19.             public void ShowResult()  
  20.             {  
  21.                 Console.WriteLine("Value of A:{0}",a);  
  22.                 Console.WriteLine("Value of B:{0}", b);  
  23.                 Console.WriteLine("Addition: A + B = {0}",Addition());  
  24.             }  
  25.         }  
  26.         static void Main(string[] args)  
  27.         {  
  28.   
  29.             Result R = new Result();  
  30.             R.a = 3;  
  31.             R.b = 4;  
  32.             R.ShowResult();  
  33.             Console.ReadLine();  
  34.         }  
  35.      }  
  36. }  
Internal

Output:

Internal output


In this example see Addition() is not declared with any access modifier.

Protected internal

The protected internal access modifier allows a method or member variable to be accessible to a class and it's derived classes inside the same assembly or namespace within a file. The member cannot be accessed from a class in another assembly or a file.

In other words, the protected internal access specifier allows its members to be accessed in a derived class, containing a class or classes within the same application.

Example
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     public class Protected_Internal  
  9.     {  
  10.         class DisplayWord  
  11.         {  
  12.             protected internal string word;  
  13.   
  14.             public void ShowName()  
  15.             {  
  16.                 Console.WriteLine("\n You are Enter Word :" + word);  
  17.             }  
  18.         }  
  19.           
  20.         static void Main(string[] args)  
  21.         {  
  22.             DisplayWord ND = new DisplayWord();  
  23.             Console.WriteLine("Enter Some Word :");  
  24.             ND.word = Console.ReadLine();  
  25.             ND.ShowName();  
  26.             Console.ReadLine();  
  27.              
  28.         }  
  29.      }  
  30. }  
Protected internal

Output

Protected internal output

Polymorphism

Polymorphism is different behavior in a different situation.

Polymorphism can be divided into the two parts, compile-time Polymorphism and run-time Polymorphism. It is known as static and dynamic Polymorphism. 

    Compile time / early binding / overloading / static binding
    Run time / late binding / overriding / dynamic binding

In other words, any addition operation between two numeric values it's given a return numeric and after this addition operation between two string value it's given a string value. It is called simply Polymorphism.

Polymorphism is static or dynamic type and it's decided at run time and compile time. Polymorphism is used in method overloading and operator overloading.

Function Overloading (Compile time polymorphism)

Function overloading means, in simple words, the same (one) function but works in different situations.

The following is one example of function overloading.

Example

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     public class Polymorphism  
  9.     {  
  10.         void DataDisplay(int n)  
  11.         {  
  12.             Console.WriteLine("Display numaric value:{0} ", n);  
  13.               
  14.         }  
  15.         void DataDisplay(string str)  
  16.         {  
  17.             Console.WriteLine("Display String Value:{0} ", str);  
  18.              
  19.         }  
  20.         static void Main(string[] args)  
  21.         {  
  22.             Polymorphism P = new Polymorphism();  
  23.             P.DataDisplay(404);  
  24.             P.DataDisplay("CSharp");  
  25.             Console.ReadKey();  
  26.        
  27.         }  
  28.      }  
  29. }  
Function Overloading

Output

Function Overloading output

Here in this example see DataDisplay() provides different output with different arguments.

But in this same DataDisplay() function.

Operator Overloading Example
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     class RectAngal  
  9.     {  
  10.         private int height;  
  11.         private int width;  
  12.          
  13.         public void Rectheight(int h)  
  14.         {  
  15.             height = h;  
  16.         }  
  17.         public void Rectwidth(int w)  
  18.         {  
  19.             width = w;  
  20.         }  
  21.         public int RectArea()  
  22.         {  
  23.             return height * width;  
  24.         }  
  25.         public static RectAngal operator +(RectAngal rH, RectAngal rW)  
  26.         {  
  27.             RectAngal Rect = new RectAngal();  
  28.             Rect.height = rH.height + rH.height;  
  29.             Rect.width = rH.width + rW.width;  
  30.             return Rect;  
  31.         }  
  32.     }  
  33.     public class OperatorOverload  
  34.     {  
  35.         static void Main(string[] args)  
  36.         {  
  37.             int Area1, Area2;  
  38.             RectAngal R_Angal_1_Area = new RectAngal();  
  39.             RectAngal R_Angal_2_Area = new RectAngal();  
  40.   
  41.             R_Angal_1_Area.Rectheight(5);  
  42.             R_Angal_1_Area.Rectwidth(4);  
  43.   
  44.             R_Angal_2_Area.Rectheight(3);  
  45.             R_Angal_2_Area.Rectwidth(4);  
  46.   
  47.             Area1 = R_Angal_1_Area.RectArea();  
  48.             Area2 = R_Angal_2_Area.RectArea();  
  49.   
  50.             Console.WriteLine("Rectangal 1 Area :{0} ", Area1);  
  51.             Console.WriteLine("Rectangal 2 Area :{0} ", Area2);  
  52.             Console.ReadLine();  
  53.         }  
  54.      }  
  55. }  
Output

Operator Overloading


Dynamic Polymorphism

Dynamic polymorphism is run time Polymorphism. It is also known as method overriding. Method overriding means having two or more methods with the same name and the same signature but with different implementations. In this method override so it is also called method overriding.

Method override uses the inheritance principle using the virtual and override keywords.

Example
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     class Person  
  9.     {  
  10.         public virtual void display()  
  11.         {  
  12.             Console.WriteLine(" Person ");  
  13.         }  
  14.     }  
  15.     class Student : Person  
  16.     {   
  17.         public override void display()  
  18.         {  
  19.             Console.WriteLine(" Student ");  
  20.         }  
  21.     }  
  22.     class Program  
  23.     {  
  24.         static void Main(string[] args)  
  25.         {  
  26.             Person P ;  
  27.             P= new Person();  
  28.             P.display();  
  29.   
  30.             P = new Student();  
  31.             P.display();  
  32.               
  33.             Console.ReadLine();  
  34.         }  
  35.     }  
  36. }  
Dynamic Polymorphism

Output:

Dynamic Polymorphism Output

Abstract Class and Abstract Method

Abstract Class:

The abstract keyword can be used for class and method.

An abstract class cannot be instantiated as an object and is only provided for the purpose of deriving subclasses.Abstract class have some restriction,it's cannot be constructed. Abstract method have no body.

Declare Abstract Class:
  1. public abstract class className  
  2. {  
  3.   
  4. }  
When a class is declared as abstract class, then it is not possible to create an instance for that class. But it can be used as a parameter in a method.

Example
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     public abstract class BaseClass  
  9.     {  
  10.         public abstract string GetAbstractData();  
  11.   
  12.         public virtual string GetVirtualData()  
  13.         {  
  14.             return "Base Virtual Data";  
  15.         }  
  16.         public string GetData()  
  17.         {  
  18.             return "Base Get Data";  
  19.         }  
  20.     }  
  21.     public class DerivedClass : BaseClass  
  22.     {  
  23.         public override string GetAbstractData()  
  24.         {  
  25.             return "Derived Abstract Data";  
  26.         }  
  27.   
  28.         public override string GetVirtualData()  
  29.         {  
  30.             return "Derived Virtual Data";  
  31.         }  
  32.   
  33.         public string GetData()  
  34.         {  
  35.             return "Derived Get Data";  
  36.         }  
  37.     }  
  38.     class Program  
  39.     {  
  40.   
  41.         static void Main(string[] args)  
  42.         {  
  43.             BaseClass ABS = new DerivedClass();  
  44.   
  45.             Console.WriteLine(ABS.GetAbstractData());  
  46.             Console.WriteLine(ABS.GetVirtualData());  
  47.             Console.WriteLine(ABS.GetData());  
  48.   
  49.   
  50.             DerivedClass DRD = new DerivedClass();  
  51.   
  52.             Console.WriteLine(DRD.GetAbstractData());  
  53.             Console.WriteLine(DRD.GetVirtualData());  
  54.             Console.WriteLine(DRD.GetData());  
  55.   
  56.   
  57.             Console.ReadLine();  
  58.         }  
  59.     }  
  60. }  
Output

Abstract Class

Dynamic Polymorphism with Abstract Class and virtual method:

Some keyword is used for inheritance in Object Oriented Programming language.

Abstract and virtual use in csharp. And also override any method using this.

Here given one example for Abstract class and virtual method.

Example
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     public abstract class BaseClass  
  9.     {  
  10.         public abstract string GetAbstractData();  
  11.   
  12.         public virtual string GetVirtualData()  
  13.         {  
  14.             return "Base Virtual Data";  
  15.         }  
  16.         public string GetData()  
  17.         {  
  18.             return "Base Get Data";  
  19.         }  
  20.     }  
  21.     public class DerivedClass : BaseClass  
  22.     {  
  23.         public override string GetAbstractData()  
  24.         {  
  25.             return "Derived Abstract Data";  
  26.         }  
  27.   
  28.         public override string GetVirtualData()  
  29.         {  
  30.             return "Derived Virtual Data";  
  31.         }  
  32.   
  33.         public string GetData()  
  34.         {  
  35.             return "Derived Get Data";  
  36.         }  
  37.     }  
  38.     class Program  
  39.     {  
  40.   
  41.         static void Main(string[] args)  
  42.         {  
  43.             BaseClass ABS = new DerivedClass();  
  44.   
  45.             Console.WriteLine(ABS.GetAbstractData());  
  46.             Console.WriteLine(ABS.GetVirtualData());  
  47.             Console.WriteLine(ABS.GetData());  
  48.   
  49.   
  50.             DerivedClass DRD = new DerivedClass();  
  51.   
  52.             Console.WriteLine(DRD.GetAbstractData());  
  53.             Console.WriteLine(DRD.GetVirtualData());  
  54.             Console.WriteLine(DRD.GetData());  
  55.   
  56.   
  57.             Console.ReadLine();  
  58.         }  
  59.       
Output: 1

Output 1

Now, see one more outputs with this example but remove.
  1. GetVirtualData()  
  2. GetData()  
Method from Deriverd Class and see the output, what's happenning.

Output: 2

Output 2

Sealed Class

A Sealed Class means, in normal words, your class is sealed or restricted from being inherited by any other class. A Sealed class is created with the sealed keyword with the class name.

A Sealed class cannot be derived from.

Example
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     
  9.     class Program  
  10.     {  
  11.         public abstract class Triangle  
  12.         {  
  13.             private double W;  
  14.             private double H;  
  15.   
  16.             public Triangle(double length = 0D, double height = 0D)  
  17.             {  
  18.                 W = length;  
  19.                 H = height;  
  20.             }  
  21.   
  22.             public virtual double Area()  
  23.             {  
  24.                 return W * H / 2;  
  25.             }  
  26.   
  27.             public void Display(string D = "")  
  28.             {  
  29.                 Console.WriteLine("Triangle  {0}", D);  
  30.                 Console.WriteLine("--------------------------");  
  31.                 Console.WriteLine("Triangle Width:    {0}", W);  
  32.                 Console.WriteLine("Triangle Height:   {0}", H);  
  33.                 Console.WriteLine("Triangle Area:     {0}", Area());  
  34.             }  
  35.         }  
  36.   
  37.         sealed public class SealedDemo : Triangle  
  38.         {  
  39.             public SealedDemo(double Width, double Height): base(Width, Height)  
  40.             {  
  41.             }  
  42.         }  
  43.         static void Main(string[] args)  
  44.         {  
  45.             SealedDemo SD = new SealedDemo(5.3, 8.5);  
  46.             SD.Display("         OUTPUT");  
  47.             Console.ReadLine();  
  48.         }  
  49.     }  
  50. }  
Output

Sealed Class

Inheritance

Inheritance is one of the most important primary concepts of OOP. Inheritance provides existing code reusability in a programming language.

Implement Base class and Derived Class. And Initialize Base Class from Derived Class. C# supports single class inheritance only.

Example

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     class RectangleValue    //Base Class  
  9.     {  
  10.         protected int height, width;  
  11.   
  12.         public void Rect_Hight(int h)  
  13.         {  
  14.             height = h;  
  15.         }  
  16.         public void Rect_Width(int w)  
  17.         {  
  18.            width = w;  
  19.         }  
  20.     }  
  21.   
  22.     class Rectangle : RectangleValue    // RectangleValue Resue   
  23.     {  
  24.         public int RectangleArea()  
  25.         {  
  26.             return (height * width);  
  27.         }  
  28.     }  
  29.     class Inheritance  
  30.     {  
  31.         static void Main(string[] args)  
  32.         {  
  33.             Rectangle R = new Rectangle();  
  34.             R.Rect_Hight(5);  
  35.             R.Rect_Width(8);  
  36.             Console.WriteLine("RectAngle Area:{0}", R.RectangleArea());  
  37.             Console.ReadLine();  
  38.         }  
  39.     }  
  40. }  
Output

Inheritance


In this see the preceding example RectangleValue class create one time and use in other class for finding Rectangle Area. C# is not support multiple inheritance.

So in C# provide multi inheritance using interface.

Interface

Interface like one type of class but not implement, but only declare with any method or properties. Program easily maintain with interface. Here give interface inheritance example.using with the preceding example.

Example
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {  
  8.     class RectangleValue    //Base Class  
  9.     {  
  10.         protected int height, width;  
  11.   
  12.         public void Rect_Hight(int h)  
  13.         {  
  14.             height = h;  
  15.         }  
  16.         public void Rect_Width(int w)  
  17.         {  
  18.            width = w;  
  19.         }  
  20.     }  
  21.   
  22.     public interface TriAngle  
  23.     {  
  24.         int TriAngleArea(int area);  
  25.   
  26.     }  
  27.   
  28.   
  29.   
  30.     class Rectangle : RectangleValue, TriAngle   // using interface class   
  31.     {  
  32.         public int RectangleArea()  
  33.         {  
  34.             return (height * width);  
  35.         }  
  36.         public int TriAngleArea(int area)  
  37.         {  
  38.             return area/2;  
  39.         }  
  40.     }  
  41.   
  42.   
  43.     class Inheritance  
  44.     {  
  45.         static void Main(string[] args)  
  46.         {  
  47.             int area;  
  48.             Rectangle R = new Rectangle();  
  49.             R.Rect_Hight(5);  
  50.             R.Rect_Width(8);  
  51.             area = R.RectangleArea();  
  52.             Console.WriteLine("RectAngle Area:{0}", R.RectangleArea());  
  53.             Console.WriteLine("TriAngle Area:{0}", R.TriAngleArea(area));  
  54.             Console.ReadLine();  
  55.         }  
  56.     }  
  57. }  
Output

Interface

Constructor And Destructor

Constructor

A constructor is one method of initializing a class.

A constructor has no return type. A constructor is called automatically by the object of the class and it initializes the class member.

    I. Default Constructor

    If no parameter is passed in the constructer then it's called the default constructor.

    Example

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5.   
    6. namespace OPPS  
    7. {      
    8.     class Constructor  
    9.     {          
    10.         class DefaultConstructor  
    11.         {   
    12.             int a, b;  
    13.             public DefaultConstructor()  
    14.             {  
    15.                 a=5;   
    16.                 b=10;  
    17.             }  
    18.             public void OutPut()  
    19.             {  
    20.             Console.WriteLine("Value of A = {0}",a);  
    21.             Console.WriteLine("Value of B = {0}", b);  
    22.             }  
    23.         }  
    24.         static void Main(string[] args)  
    25.         {  
    26.             DefaultConstructor DC = new DefaultConstructor();  
    27.             DC.OutPut();  
    28.             Console.ReadLine();  
    29.         }  
    30.     }  
    31. }  
    Output

    Default Constructor

    II. Parameterized Constructor

    In a Parameterized Constructor at least one parameter is passed to the constructor.

    Example
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5.   
    6. namespace OPPS  
    7. {      
    8.     class Constructor  
    9.     {  
    10.         class PerameterConstructor  
    11.         {   
    12.             int a, b;  
    13.             public PerameterConstructor(int i, int j)       // Pass parameter  
    14.             {  
    15.                 a=i;   
    16.                 b=j;  
    17.             }  
    18.             public void OutPut()  
    19.             {  
    20.             Console.WriteLine("Value of A = {0}",a);  
    21.             Console.WriteLine("Value of B = {0}", b);  
    22.             }  
    23.         }  
    24.         static void Main(string[] args)  
    25.         {  
    26.             PerameterConstructor DC = new PerameterConstructor(5,3);      // Pass parameter value  
    27.             DC.OutPut();  
    28.             Console.ReadLine();  
    29.         }  
    30.     }  
    31. }  
    Output

    Parameterized Constructor

    III. Copy Constructor

    A Copy Constructor is a constructor that creates a new object by making a copy of an existing object.

    Example
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Linq;  
    4. using System.Text;  
    5.   
    6. namespace OPPS  
    7. {      
    8.     class Constructor  
    9.     {  
    10.         class CopyConstructor  
    11.         {   
    12.             int a, b;  
    13.             public CopyConstructor(int i, int j)     
    14.             {  
    15.                 a=i;   
    16.                 b=j;  
    17.             }  
    18.             public CopyConstructor( CopyConstructor c)  
    19.             {  
    20.                 a = c.a;  
    21.                 b = c.b;  
    22.             }  
    23.             public void OutPut()  
    24.             {  
    25.             Console.WriteLine("Value of A = {0}",a);  
    26.             Console.WriteLine("Value of B = {0}", b);  
    27.             }  
    28.         }  
    29.         static void Main(string[] args)  
    30.         {  
    31.             CopyConstructor CC = new CopyConstructor(5,3);       
    32.             CopyConstructor copy = new CopyConstructor(CC);  
    33.             CC.OutPut();  
    34.             Console.WriteLine("------- VALUE COPY ----------");  
    35.             copy.OutPut();  
    36.             Console.ReadLine();  
    37.         }  
    38.     }  
    39. }  
    Output

    copy

    IV. Static Constructor

    Static constructors are also called class constructors. A static constructor is triggered to run immediately before the first static method on its class is called, or immediately before the first instance of its class is created. A static constructor cannot be a parameterized constructor.

    Example
    1. namespace OPPS  
    2. {      
    3.     class Static  
    4.     {  
    5.         class Base  
    6.         {  
    7.             static Base()   
    8.             {  
    9.                 Console.WriteLine("Base");   
    10.             }  
    11.             public Base()   
    12.             {   
    13.                 Console.WriteLine("Base");   
    14.             }  
    15.               
    16.         }  
    17.         class Derived : Base  
    18.         {  
    19.             static Derived()   
    20.             {   
    21.                 Console.WriteLine("Derived");   
    22.             }  
    23.             public Derived()   
    24.             {   
    25.                 Console.WriteLine("Derived");   
    26.             }  
    27.              
    28.         }  
    29.         static void Main(string[] args)  
    30.         {  
    31.             Console.WriteLine("Static Demo");  
    32.             new Derived();  
    33.             Console.ReadLine();  
    34.         }  
    35.     }  
    36. }  
    Output

    Static Constructor

     

Private Constructor

A private constructor cannot be inherited. And a private constructor class is accessed with a private access modifier. It is not possible to directly create the class object.

Example

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace OPPS  
  7. {      
  8.     class Private  
  9.     {  
  10.         public class PageHit  
  11.         {  
  12.             private PageHit()   
  13.             {  
  14.             }  
  15.             public static int currentCount;  
  16.             public static int IncrementCount()  
  17.             {  
  18.                 return currentCount++;  
  19.             }  
  20.         }  
  21.           
  22.         static void Main(string[] args)  
  23.         {  
  24.             PageHit.currentCount = 20;  
  25.             PageHit.IncrementCount();  
  26.             Console.WriteLine("Number of time Page Hit: {0}", PageHit.currentCount);  
  27.             Console.ReadLine();  
  28.         }  
  29.     }  
  30. }  
Output

Private Constructor


In this example see PageHit.currentCount = 20 and when you run program +1 count and given output 21.

Destructor

A destructor is used to destroy a class. Any one class has only one destructor.

A destructor is a method in the class with the same name as the class preceded with the ~ symbol.

Command:

    ~ ClassName()
    {
    }

Example

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace OPPS  
  6. {  
  7.    public class DemoClass  
  8.    {  
  9.       public DemoClass()  
  10.       {  
  11.          Console.WriteLine("Create Class");  
  12.       }  
  13.       ~DemoClass()  
  14.       {  
  15.          Console.WriteLine("Class Destroyed");  
  16.       }  
  17.    }  
  18.    class Destructor  
  19.    {  
  20.       public static void DC_Create()  
  21.       {  
  22.          DemoClass DC = new DemoClass();  
  23.       }  
  24.       static void Main(string[] args)  
  25.       {  
  26.          DC_Create();  
  27.          GC.Collect();  
  28.          Console.ReadLine();  
  29.       }  
  30.    }  
  31. }  

 

Output