Abstraction implementation in C#

 In object-oriented programming, Abstraction is the process of hiding certain details and showing only essential information to the user.

Why Abstraction is needed?

Abstraction allows us to create a general idea of what the problem is and how to solve it. The process instructs us to remove all specific detail and any patterns that will not help us solve our problem.

In C#, Abstraction can be achieved by using Abstract Class(es) and Interface(s).

Let's take an example to implement this with C#:

namespace Abstraction;
public interface IDevice
{
public string GetDeviceType();
}
public class Android : IDevice
{
public string GetDeviceType()
{
return "Android";
}
}
public class IPhone : IDevice
{
public string GetDeviceType()
{
return "IPhone";
}
}
public class Window : IDevice
{
public string GetDeviceType()
{
return "Window";
}
}
public static class DeviceManager
{
public static IDevice GetDevice(string device)
{
return device switch
{
"Android" => new Android(),
"IPhone" => new IPhone(),
"Window" => new Window(),
_ => null,
};
}
}
public class Program
{
public static void Main(string[] args)
{
Print(DeviceManager.GetDevice("Android"));
Print(DeviceManager.GetDevice("IPhone"));
Print(DeviceManager.GetDevice("Window"));
}
private static void Print(IDevice device)
{
Console.WriteLine(device.GetDeviceType());
}
}
view raw Program.cs hosted with ❤ by GitHub


In the preceding example, we have achieved abstraction with the help of the IDevice interface, which is implemented by the Android, IPhone, and Window concrete classes. So, to keep abstraction between concrete implementation and users, we used a DeviceManager class, which is responsible to provide the instance of the specific device based on provided device type. In the DeviceManager class,  the GetDevice() method returns an instance of the IDevice interface type instead of concrete classes (Android, IPhone, and Window). 

Here, the users don't know about concrete implementation, they know about the problem and how to solve it.

Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form