Home > Articles > Programming > C#

Using C# Interfaces

Like this article? We recommend

C# Interfaces and Inheritance

Using interfaces as in Listing 1 is useful because it allows you to define little pockets of functionality. Any implementing classes can provide the code to fulfill the interface contract. However, the real power of interfaces comes from inheritance, as illustrated in Listing 2.

Listing 2 Interfaces and inheritance.

public interface IMyBaseInterface
{
  void DoSomethingBasic();
}

public interface IMyInterface : IMyBaseInterface
{
  void DoSomethingOrOther();
}

class MainClass : IMyInterface
{
  public void DoSomethingOrOther()
  {
    Console.WriteLine("Now doing something");
    Console.ReadLine();
  }

public void DoSomethingBasic()
{
  Console.WriteLine("Now doing something basic");
  Console.ReadLine();
}

public static void Main(string[] args)
{
  Console.WriteLine("Hello World!");
  MainClass mainClass = new MainClass();
  mainClass.DoSomethingOrOther();
  mainClass.DoSomethingBasic();
}

Notice the way in which the MainClass class implicitly acquires the base interface IMyBaseInterface. This is because the other interface automatically pulls that interface along with it, and the implementing class must then provide code for the methods in both interfaces. This example illustrates the important point that interfaces are lightweight contract entities, and client code must provide the contents; in other words, the method code.

It's perhaps a little surprising that C# interfaces can also be treated as parameters, as shown in Listing 3.

Listing 3 An interface treated as a parameter.

Console.WriteLine("Hello World!");
MainClass mainClass = new MainClass();
mainClass.DoSomethingOrOther();
mainClass.DoSomethingBasic();

IMyBaseInterface iMyBaseInterface;
iMyBaseInterface = mainClass;
iMyBaseInterface.DoSomethingBasic();

In Listing 3, we can treat the IMyBaseInterface interface as a parameter because the MainClass class implements this interface. Because of this relationship, we know that an object or instance of this class (such as the mainClass object) also implements the interface. This gives rise to the somewhat unexpected syntax in Listing 3.

Another important aspect of interfaces is versioning. If you define an interface and one or more classes that implement it, it's a good practice to include version data. Listing 4 shows a modified interface that includes a version number.

Listing 4 A versioned interface.

public interface IMyInterface : IMyBaseInterface
{
  void DoSomethingOrOther();
  byte Version{get;}
}

To use this new interface, you simply implement the accessor in the MainClass class (see Listing 5).

Listing 5 A versioned interface.

class MainClass : IMyInterface
{
  public void DoSomethingOrOther()
  {
   Console.WriteLine("Now doing something");
   Console.ReadLine();
  }

  public byte Version
  {
   get { return 1;}
  }

  public void DoSomethingBasic()
  {
   Console.WriteLine("Now doing something basic");
   Console.ReadLine();
  }

  public static void Main(string[] args)
  {
   Console.WriteLine("Hello World!");
   MainClass mainClass = new MainClass();
   mainClass.DoSomethingOrOther();
   mainClass.DoSomethingBasic();
   Console.WriteLine("Version data: {0}", mainClass.Version);
  }
}

Versioning interfaces in this way allows for the interface contract to be upheld. Rather than just changing an interface, you can inherit from the interface and create a new one. Also, the version number can be updated in the classes that implement the extended interface. Let's see how this might work in practice.

Suppose we have our existing interfaces as in Listings 1–5, and now we want to add another method to IMyInterface. If the existing version of the code has been released, we should assume that there are classes that implement the interfaces. If we change the interfaces now, the existing client code will break—that is, it will no longer compile. The correct way to update the interface is to create a new one (called IMyUpdatedInterface in Listing 6) that derives from the interface we want to modify (in this case, IMyBaseInterface).

Listing 6 Adding code to an existing interface.

public interface IMyBaseInterface
{
  void DoSomethingBasic();
}

public interface IMyInterface : IMyBaseInterface
{
  void DoSomethingOrOther();
  byte Version{get;}
}

public interface IMyUpdatedInterface : IMyInterface
{
  void DoSomethingNew();
}

With this change, any client code that needs the new interface can implement it without breaking existing code. The interface version number is entirely optional, but it might be useful as a marker.

What about situations where your C# codebase has many interfaces, and you want to determine which interfaces a given object implements? A few mechanisms exist for handling this problem. We'll look at those next.

Determining Whether a Type Supports an Interface

Suppose you want find out whether a given object supports one of your interfaces. This is possible using the as keyword (see Listing 7).

Listing 7 Determining whether a type supports a given interface.

class MainClass : IMyUpdatedInterface
  {
   public void DoSomethingOrOther()
   {
     Console.WriteLine("Now doing something");
     Console.ReadLine();
   }

   public byte Version
   {
     get { return 1;}
   }

   public void DoSomethingNew()
   {
     Console.WriteLine("Now doing something new");
     Console.ReadLine();
   }

   public void DoSomethingBasic()
   {
     Console.WriteLine("Now doing something basic");
     Console.ReadLine();
   }

   public static void Main(string[] args)
   {
     Console.WriteLine("Hello World!");
     MainClass mainClass = new MainClass();
     mainClass.DoSomethingOrOther();
     mainClass.DoSomethingBasic();
     Console.WriteLine("Version data: {0}", mainClass.Version);

     IMyBaseInterface iMyBaseInterface;
     iMyBaseInterface = mainClass;
     iMyBaseInterface.DoSomethingBasic();

     mainClass.DoSomethingNew();

     IMyUpdatedInterface iUpdatedIf = mainClass as IMyUpdatedInterface;

     if (iUpdatedIf != null)
     {
      Console.WriteLine("Interface is supported");
      iUpdatedIf.DoSomethingBasic();
     }
      else
      Console.WriteLine("Interface not supported");
   }
  }

Notice that I changed the very first line of Listing 7 so that the class MainClass implements IMyUpdatedInterface, to ensure that the object of MainClass implements the required interface. Without this code change, the attempt t o obtain a reference to the interface would fail.

Another approach to the same problem is to use the is keyword, as illustrated in Listing 8.

Listing 8 Determining interface support by using the is keyword.

IMyUpdatedInterface iUpdatedIf1 = mainClass;
if (iUpdatedIf1 is IMyUpdatedInterface)
  {
   Console.WriteLine("This interface is also supported");
   iUpdatedIf.DoSomethingBasic();
  }
else
  Console.WriteLine("Interface not supported");

The use of the is keyword is a handy alternative to the as keyword. Whichever method you choose, the important point is that you don't risk throwing an exception. The invalid cast in Listing 9 would cause a System.InvalidCastException to be thrown.

Listing 9 This invalid cast causes an exception.

IMyCompletelyNewInterface iItf = (IMyCompletelyNewInterface) mainClass;

In Listing 9, the interface IMyCompletelyNewInterface is not implemented by the MainClass class, so we get an exception. However, using the techniques with the is or as keywords avoids the exception problem. In general, it's far better to avoid throwing exceptions when you can. Exception-free code tends to run faster and requires less code (try-catch blocks).

C# Inheritance

One of the main merits of inheritance is the way you can use it to hide complex details. A properly designed class hierarchy helps in pushing common code up the way; in other words, the subclasses can inherit only what they need. Common code can live at the top of the hierarchy, while more specific code lives lower down the hierarchy. This separation helps to reduce clutter in subclasses. An additional benefit is less need for duplicated code. One important design question occurs, though: Why would you use C# interfaces instead of abstract base classes? Let's consider that issue next.

Inheritance: C# Interfaces and C# Abstract Classes

Perhaps the nicest thing about C# interfaces is their very lightweight nature. You simply define an interface to represent some item of functionality. There's no need to define any additional boilerplate code. The situation isn't the same for abstract base classes, because a class by nature tends to be a more heavyweight entity.

Listing 10 illustrates an abstract base class and an implementing concrete class.

Listing 10 Abstract base class and concrete class.

  public abstract class AnAbstractClass
  {
   public abstract void DoSomethingBasic();
   public abstract void DoSomethingOrOther();
  }

  public class AConcreteClass : AnAbstractClass
  {
   public override void DoSomethingBasic()
   {
     Console.WriteLine("Now doing something in the concrete class");
     Console.ReadLine();
   }

   public override void DoSomethingOrOther()
   {
     Console.WriteLine("Now doing something or other in the concrete class");
     Console.ReadLine();
   }
  }

As is the case with interfaces, abstract base classes are placeholders for code. The abstract methods must be implemented by subclasses—in this case, AConcreteClass. Why would you use an abstract base class instead of an interface? Well, the choice is partly style, but it also depends on whether you want a more heavyweight base entity. If you want to define a very specific type of base entity, an abstract base class may be a good choice. One point to bear in mind, however, is that the base class may itself inherit from other classes.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020