An Introduction to Interfaces in C#

C# Tutorials
In the C# programming language, an interface is one of the most powerful features. There have been several changes in interfaces in recent versions of the C# language. This programming tutorial talks about interfaces in C#, their benefits, and how they can be used through code examples.

What is an Interface in C#?

In C#, an interface is analogous to a contract that does not have any implementation. Interfaces allow developers to define a common set of capabilities that can be used by all classes that implement them, providing a great way to structure your code and make it more organized and maintainable.

Note that an interface must be public – programmers cannot declare an interface as private, protected, protected internal, or private protected. Interfaces are useful for defining contracts between components.

For example, if you have a component that needs to retrieve data from a database, you can define an interface that includes a method for retrieving data. Programmers should provide the necessary implementation in the implementing class, (i.e., the class that implements this interface).

Before going further, if you need to brush up on your knowledge of C# object oriented programming principles, we suggest you check out the following tutorials:

Recent Changes to Interfaces Since C# 8.0

In the earlier versions of the C# language, (i.e., prior to C# 8.0) an interface may only have method declarations and not method definitions. However, with C# 8.0, methods of an interface can have implementations.

Prior to C# 8.0, an interface could not have fields or private, protected, or internal members. If you added a new member (such as a method declaration) to an interface, you would have to update all of the classes that implement the interface.

You can also have virtual or abstract members in an interface. However, an interface cannot contain an instance member. This explains why you cannot serialize an interface because serialization works with data, not operations.

What is the Differences between an Interface and Abstract Class in C#?

Developers can create concrete and non-concrete methods in an abstract class. It is up to the derived classes to implement the abstract or virtual members. If you are using an earlier version of C# and interfaces, you are constrained to implementing all methods of the interface in the class that extends the interface. However, this is no longer required with C# 8.0.

An interface cannot include any member data. An abstract class can have fields, constructors, and methods, but an interface can only declare events, methods, and properties. All of the interface’s members should be implemented by the class that implements it. You cannot create objects of an interface.

If you have plans for future development, such as class hierarchy expansion, an abstract class is a smart solution. On a side note, an interface is a good choice if you need to build a contract on some behaviour or feature. Use interfaces to isolate your application’s code from particular implementations or to limit access to elements of a given type.

Now, since interfaces have been updated with the recent versions of the C# language, should you use an interface or an abstract class? Well, the choice between an interface and an abstract class depends on whether you would like to implement late binding in the derived classes.

Read: Introduction to Constructors in C#

How to Program Interfaces in C#

Consider the following class:

public class Customer
{
   public Guid Id = Guid.NewGuid();
   public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }    
    public string Address { get; set; }
    public string Phone { get; set; }
}

The following code example shows how you can use an interface to in C# to implement a simple functionality:

public interface IRepository
{
    public void Add(Customer customer);
}
public class Repository : IRepository
{
    public void Add(Customer customer)
    {
        //Write your implementation here
    }
}

This is an example of explicit interface implementation. You can also implement an interface implicitly in C#, as shown below:

public class Repository : IRepository
{
    void IRepository.Add(Customer customer)
    {
        //Write your implementation here
    }
}

When an interface has been implemented implicitly in a class, programmers must use the interface when creating an instance of the class. For example, you can use the following code to create an object of the class in C#:

Customer customer= new Customer();
customer.FirstName = "Joydip";
customer.LastName = "Kanjilal";
customer.Email = "myemail@email.com";
customer.Address = "Some address";
IRepository repository = new Repository();
repository.Add(customer);
However, the following code will not work:
Repository repository = new Repository();
repository.Add(customer);
An interface can also extend an interface as shown in the below code snippet:
public interface X
{
}
public interface Y : X
{
}

Default Interface Methods in C#

Starting in C# 8.0, methods in an interface can have default implementations. By using default interface methods, developers can reuse methods from unrelated types. Let’s say you made a library that many developers will use, and you want to release a revised version.

If you add new members to your interfaces, you can declare their implementations so you can keep working with the types without modifying them.

The following code example shows how you can have default method implementation in an interface in C#:

public interface ICustomerRepository
{
    public void Add(Customer customer)
    {
        //Write your implementation code here
    }
}

Final Thoughts on C# Interfaces

Interfaces are a great way to create decoupled code and make it easier to unit test. They can also be used as a type of contract that different developers can agree on when they are working together.

With interfaces, programmers can create generalized code that works with different types of objects and makes our applications more modular and extensible. Interfaces also provide an excellent way to implement dependency injection.

Read: Top Unit Testing Tools for Developers

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read