C# Abstraction with Examples

C# Abstraction with Examples 

Abstraction means displaying only essential information and hiding the details. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation.

Advantages of Data Abstraction:

  • Helps the user to avoid writing the low level code.
  • Avoids code duplication and increases reusability.
  • Can change internal implementation of class independently without affecting the user.
  • Helps to increase security of an application or program as only important details are provided to the user.

Abstraction can be achieved using abstract classes in C#. C# allows you to create abstract classes that are used to provide a partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality.

The following are some of the key points for abstract class −

  • You cannot create an instance of an abstract class.
  • You cannot declare an abstract method outside an abstract class.
  • When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.

C# Abstraction with Examples  :

Following is the example of implementing an abstraction functionality by allowing only few properties and methods to access outside of the class in c# programming language.

using System;
namespace OppsConcept
    class Program
        static void Main(string[] args)
            Rectangle r = new Rectangle(25, 17);
            double a = r.area();
            Console.WriteLine("Area: {0}", a);

        abstract class Shape
            public abstract int area();

        class Rectangle : Shape
            private int length;
            private int width;

            public Rectangle(int a = 0, int b = 0)
                length = a;
                width = b;
            public override int area()
                Console.WriteLine("Area of Rectangle:");
                return (width * length);

If you observe above example, we defined a fields, properties and methods with public, private access modifiers to allow or disallow properties, methods access based on requirements.

When we execute above c# program, we will get the result like as shown below.

C# Abstraction with Examples

Difference between Abstraction and Encapsulation

Abstraction Encapsulation
It is used to hide unwanted data and show only required properties and methods. It is used to bind data members and member functions into single unit to prevent outsiders to access it directly


Also Learn More Tutorial :


Leave a Reply

Your email address will not be published.