Resources » .NET programming » General

OOPs Concepts in C#


Posted Date: 20-Jun-2008  Last Updated:   Category: General    
Author: Member Level: Gold    Points: 15


Are you searching the concept of OOPs in c-sharp(c#)? This article helps you to clear your understanding on the topic the concept of Object Oriented Programming System.



OOPs Concepts in C#



I will discuss these topics in this Article

  • Polymorphism
  • Inheritance
  • Abstraction
  • Encapsulation


    Inheritance



    One of the key concepts of Object Oriented Programming is inheritance. With inheritance, it is possible to create a new class from an existing one and add new features to it. Thus inheritance provides a mechanism for class level re-usability. The new programming language C# also supports inheritance. The syntax is straightforward.

      
    class Base
    {
    }

    class Derived : Base
    {
    }


    The operator ":"is used to indicate that a class is inherited from another class. Remember that in C#, a derived class can't be more accessible than it's base class. That means that it is not possible to declare a derived class as public, if it inherits from a private class. For example the following code will generate a compile time error.

      
    class Base
    {
    }

    public class Derived : Base
    {
    }


    In the above case the Base class is private. And we are trying to inherit a public class from a private class.

    Let us look at a concrete example.

    Here, Derived class inherits public members of the Base class x,y and Method(). The objects of the Derived class can access these inherited members along with its own member z.

      
    using System;
    class Base
    {
    public int x = 10;
    public int y = 20;
    public void Method()
    {
    Console.WriteLine("Base Method");
    }
    }
    class Derived : Base
    {
    public int z = 30;
    }
    class MyClient
    {
    public static void Main()
    {
    Derived d1 = new Derived();
    Console.WriteLine("{0},{1},{2}",d1.x,d1.y,d1.z); // displays 10,20,30
    d1.Method();// displays 'Base Method'
    }
    }


    Inheritance & Access Modifiers



    A derived class inherits every thing from the base class except constructors and destructors. The public members of the Base class becomes the public members of the Derived class also. Similarly the protected members of the base class become protected members of the derived class and internal member becomes internal members of the derived class. Even the private members of the base class are inherited to the derived class, even though derived class can't access them.


    Inheritance & Data Members



    We know all base class data members are inherited to the derived, but their accessibility remains unchanged in the derived class. For example in the program given below

      
    using System;
    class Base
    {
    public int x = 10;
    public int y = 20;
    }
    class Derived : Base
    {
    public int z = 30;
    public void Sum()
    {
    int sum = x+y+z;
    Console.WriteLine(sum);
    }
    }
    class MyClient
    {
    public static void Main()
    {
    Derived d1 = new Derived();
    d1.Sum();// displays '60'
    }
    }


    Here class Derived have total three data members, two of them are inherited from the Base class.

    In C#, even it is possible to declare a data member with the same name in the derived class as shown below. In this case, we are actually hiding a base class data member inside the Derived class. Remember that, still the Derived class can access the base class data member by using the keyword base .


    using System;
    class Base
    {
    public int x = 10;
    public int y = 20;
    }
    class Derived : Base
    {
    public int x = 30;
    public void Sum()
    {
    int sum = base.x+y+x;
    Console.WriteLine(sum);
    }
    }
    class MyClient
    {
    public static void Main()
    {
    Derived d1 = new Derived();
    d1.Sum();// displays '60'
    }
    }


    But when we compile the above program, the compiler will show a warning, since we try to hide a Base class data member inside the Derived class. By using the keyword new along with the data member declaration inside the Derived class, it is possible to suppress this compiler warning. The keyword new tells the compiler that we are trying to explicitly hiding the Base class data member inside the Derived class. Remember that we are not changing the value of the Base class data member here. Instead we are just hiding or shadowing them inside the Derived class. However the Derived class can access the base class data member by using the base operator.


     
    using System;
    class Base
    {
    public int x = 10;
    public int y = 20;
    }
    class Derived : Base
    {
    public new int x = 30;
    public void Sum()
    {
    int sum = base.x+y+x;
    Console.WriteLine(sum);
    }
    }
    class MyClient
    {
    public static void Main()
    {
    Derived d1 = new Derived();
    d1.Sum();// displays '60'
    }
    }


    Inheritance & Member Functions



    What ever we discussed for data members are valid for member functions also. A derived class member function can call the base class member function by using the base operator. It is possible to hide the implementation of a Base class member function inside a Derived class by using the new operator. When we declare a method in the Derived class with exactly same name and signature of a Base class method, it is known as method hiding'. But during the compilation time, the compiler will generate a warning. But during run-time the objects of the Derived class will always call the Derived class version of the method. By declaring the derived class method as new, it is possible to suppress the compiler warning.


      
    using System;
    class Base
    {
    public void Method()
    {
    Console.WriteLine("Base Method");
    }
    }
    class Derived : Base
    {
    public void Method()
    {
    Console.WriteLine("Derived Method");
    }
    }
    class MyClient
    {
    public static void Main()
    {
    Derived d1 = new Derived();
    d1.Method(); // displays 'Derived Method'
    }
    }


    Uses of new and base operators are given in the following program.


    using System;
    class Base
    {
    public void Method()
    {
    Console.WriteLine("Base Method");
    }
    }
    class Derived : Base
    {
    public new void Method()
    {
    Console.WriteLine("Derived Method");
    base.Method();
    }
    }
    class MyClient
    {
    public static void Main()
    {
    Derived d1 = new Derived();
    d1.Method(); // displays 'Derived Method' followed by 'Base Method'
    }
    }



    Inheritance & Constructors



    The constructors and destructors are not inherited to a Derived class from a Base class. However when we create an object of the Derived class, the derived class constructor implicitly call the Base class default constructor. The following program shows this.


    using System;
    class Base
    {
    public Base()
    {
    Console.WriteLine("Base class default constructor");
    }
    }
    class Derived : Base
    {
    }
    class MyClient
    {
    public static void Main()
    {
    Derived d1 =new Derived();// Displays 'Base class default constructor'
    }
    }


    Remember that the Derived class constructor can call only the default constructor of Base class explicitly. But they can call any Base class constructor explicitly by using the keyword base.

      
    using System;
    class Base
    {
    public Base()
    {
    Console.WriteLine("Base constructor1");
    }
    public Base(int x)
    {
    Console.WriteLine("Base constructor2");
    }
    }
    class Derived : Base
    {
    public Derived() : base(10)// implicitly call the Base(int x)
    {
    Console.WriteLine("Derived constructor");
    }
    }
    class MyClient
    {
    public static void Main()
    {
    Derived d1 = new Derived();// Displays 'Base constructor2 followed by 'Derived Constructor''
    }
    }


    Note that by using base() the constructors can be chained in an inheritance hierarchy.


    Polymorphism & Virtual Methods



    A virtual method in C# specifies an implementation of a method that can be polymorphicaly overridden derived method. A non-virtual method can't be polymorphically override in a Derived class.

    A virtual method can be declared by using the keyword virtual as follows.

      
    class Base
    {
    public virtual void Method()
    {
    }
    }


    When we declare a virtual method, it must contain a method body. Other wise the compiler will generate an error. Remember that, since virtual methods are used for achieving polymorphism and since polymorphism works only with objects, it not possible to declare a static method as virtual in C#. Similarly the private methods are also not possible to declare virtual, since they can't override inside a derived class.

    In C#, it is not necessary to override a Base class virtual method inside a Derived class.

    The following program will work absolutely correct.


    using System;
    class Base
    {
    public virtual void Method()
    {
    Console.WriteLine("Base method");
    }
    }
    class Derived : Base
    {
    }
    class MyClient
    {
    public static void Main()
    {
    Derived d1 = new Derived();
    d1.Method(); // Displays 'Base Method'
    }
    }


    Or even it is possible to override a virtual method non-polymorphically inside a Derived class as shown below.

      
    using System;
    class Base
    {
    public virtual void Method()
    {
    Console.WriteLine("Base method");
    }
    }
    class Derived : Base
    {
    public virtual void Method()
    {
    Console.WriteLine("Derived method");
    }
    }
    class MyClient
    {
    public static void Main()
    {
    Derived d1 = new Derived();
    d1.Method(); // Displays 'Derived Method'
    }
    }


    Even it is possible to omit the keyword virtual from the Derived class method or it is possible to declare the Derived class method as new.

    When we want to override a virtual method polymorphically inside a Derived class, we have to use the keyword override along with the method declaration. The example is shown below.

    In C#, a Base class reference can hold an object of the Derived class and when it invokes the methods, it will invoke always the Derived class methods, if you already override that method inside the Derived class by using the override keyword. Also the Base class method must declare using the keyword virtual. This is what is known as Polymorphism in C#.


    using System;
    class Base
    {
    public virtual void Method()
    {
    Console.WriteLine("Base method");
    }
    }
    class Derived : Base
    {
    public override void Method()
    {
    Console.WriteLine("Derived method");
    }
    }
    class MyClient
    {
    public static void Main()
    {
    Base b1 = new Derived();
    b1.Method(); // Displays 'Base Method'
    }
    }


    As with a virtual method, we must include a method body with an override method; other wise the compiler will generate an error during compilation.

    Remember that in C#, we can use the override keyword with only virtual method, when overriding inside a Derived class. An overridden declaration must be identical in every way to the virtual method, it overrides. They must have the same access level; the same return type, the same name and same method signature. The overridden methods are implicitly virtual in nature and hence they can override in subsequent Derived classes. As like virtual methods, override methods can't be declared as static or private.

    In Object Oriented programming Encapsulation is the first pace. Encapsulation is the procedure of covering up of data and functions into a single unit (called class). An encapsulated object is often called an abstract data type.


  • Did you like this resource? Share it with your friends and show your love!

    Responses to "OOPs Concepts in C#"
    Author: Modi Ashfaq Ahmed    03 Dec 2010Member Level: Silver   Points : 0
    good article, very very useful for me,
    thanks for sharing and keep the good work going.

    regards
    Ashfaq Modi.



    Author: Jayendra Kumar    05 Dec 2010Member Level: Gold   Points : 1
    Thanks for sharing such a good information about oops is c#. This is good article.


    Guest Author: Dhruva     24 Nov 2011
    Good one, But required more clear information regarding virtual functions


    Author: Abhijith Rohit    21 May 2012Member Level: Silver   Points : 1
    In the ending of the article you have said that a virtual method can be overridden in child class by using the keyword overide and when the reference variable of parent class calls the same method then only derived class overridden methods are called but in the example the base class method is called ......how is this possible


    Author: Shivshanker Cheral    21 May 2012Member Level: Gold   Points : 0
    Hi Abhijith Rohit,

    Good catch! yes it will display as "Derived method" not the "Base method" its a typing mistake.

    Thanks



    Author: Abhijith Rohit    21 May 2012Member Level: Silver   Points : 1
    hi Shivshanker cheral,
    Thank you for the immediate response, i was actually confused at the end of the document but now im clear after ur reply .....plz make changes to the main document, this will be helpful for many..... this is the simple and best article with examples on oops concepts i have found so far, Keep it up....

    thanks & regards,
    Abhijith Rohit



    Author: Shivshanker Cheral    22 May 2012Member Level: Gold   Points : 1
    Here is the complete code

    public static void Main()
    {
    Base b1 = new Derived();
    b1.Method(); // Displays 'Derived method'
    b1 = new Base();
    b1.Method(); // Displays 'Base method'
    }



    Guest Author: srinivasmadduri     01 Jun 2012
    Its very useful
    thanks



    Guest Author: likitha     10 Jul 2012
    I am Beginner for C# I want detailed Explanation about it in Simple English


    Guest Author: Neha     16 Sep 2012
    Please can you tell the difference between below two:
    i)Using the "New" keyword in Derived class method
    ii) Using "Virtual" in base and "Override" keyword in derived class.



    Guest Author: himanshu     08 Jan 2013
    Thanks...


    Guest Author: anandbabu     17 Apr 2013
    excellent article to understand
    thanks.



    Guest Author: arvind     04 Jun 2013
    I am looking for a answer which may very basic but still not in my mind.

    What is the difference between Inheriting a class and instantiating a class ?

    For example in below example i have a class named "A" and class "B". B inherits A to get public members of A, I understand. But if this is only to access functions of Class "A" from Class "B", This can also be achieved by instantiation of class "A" in Class "B".



    Guest Author: priya     18 Jan 2014
    very nice article it is very useful to me.


    Feedbacks      

    Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index

    Subscribe to Subscribers
    Active Members
    TodayLast 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John

    Online Members

    Anna Nicola
    More...
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India