Interfaces in C#

Introduction

When hearing the name "Interface," one can easily guess that it's some sort of communicating media or joining line between two other mediums, namely classes here. Although the concept of interfaces in C# resembles this concept, there are few things to be made clear about this keyword and the concept behind it so that the C# programmer can best utilize its availability and can make the code more powerful.

Interfaces in C# are provided as a replacement of multiple inheritance. Because C# does not support multiple inheritance, it was necessary to incorporate some other method so that the class can inherit the behavior of more than one class, avoiding the problem of name ambiguity that is found in C++. With name ambiguity, the object of a class does not know which method to call if the two base classes of that class object contain the same named method.

The classes in C# can now make use of the keyword "interface" to inherit more than one behavior from different interfaces. When a class inherits from one or more interfaces, we say that the class is implementing that interface(s). The most important thing to remember about interfaces is that the classes can only implement the methods defined in the interface because in C#, an interface is a built-in keyword that declares a reference type that includes method declarations. In addition to methods, interfaces can define properties, indexers, and events that will be discussed later in this article.

Implementing Interfaces

First, we consider the following example that will clear the concept more. As we know that Mammals have both similar and dissimilar characteristics, so in this example, we have taken two sub-classes of Mammal: Human and Whale. Because Human is the only subclass that has the characteristic of intelligence that distinguishes it from the other subclasses of Mammal, the Human class inherits both the class Mammal and an interface IIntelligent that selectively describes it as separated from the other classes of Mammal.

using System;

namespace ConsoleApplication1
{
   public class Mammal
   {
      protected string Characteristis;
      public string characteristics
      {
         get
         {
            return this.Characteristis;
         }
         set
         {
            this.Characteristis=value;
         }
      }
   }
   interface IIntelligence
   {
      /// Interface method declaration
      bool intelligent_behavior();
   }

   class Human: Mammal, IIntelligence
   {
      public Human()
      {
          characteristics = "Human are mammals";
      }

/// Interface method definition in the class that implements it
      public bool intelligent_behavior()
      {
         Console.WriteLine("{0} and have intelligence",characteristics);
         return true
      }
   }
   class Whale: Mammal
   {
      public Whale()
      {
         characteristics = "Whale are mammals";
         Console.WriteLine("{0}",characteristics);
      }
   }
   class InterfaceApp
   {
      public static void Main(string[] args)
      {
         Whale whale = new Whale();
         Human human = new Human();
         /// The human object is casted to the interface type
         IIntelligence humanIQ = (IIntelligence)human;
         humanIQ.intelligent_behavior();

         Console.Read();
      }
   }
}

Using Methods, Indexers, Properties, and Event Declarations Within an Interface

Now, we consider the same example so as to explain the use of indexers, properties, and events within the interface. The code for the interface IIntelligent and the Main class InterfaceApp is changed.

interface IIntelligence
{
   /// Method declaration within the interface
   bool intelligent_behavior();

   /// Indexer declaration within the interface
   object this[int index]
   {
      get;
      set;
   }
   /// Event declaration within an interface
   /// testEvent should also be declared as a delegate before
   event testEvent IQEvent;

   /// Property declaration within an interface
   string IQProperty
   {
      get{}
      set{}
   }
}

Using "Is" and "As" Operators to Verify the Implementation of an Interface

Think what will happen if an object attempted to use a class as though the class had implemented a method that is not defined in it; you will get an exception at runtime. To remove this ambiguity, we use the "is" keyword to verify that the method exists in the class implementing the given interface.

I will use the same code of the Mammal class above for explaining this. Here, we need to change only the Main ( ) because we only need to check that our created object is either implementing the interface or not.

if(human is IIntelligence)

{
   IIntelligence humanIQ = (IIntelligence)human;
   humanIQ.intelligent_behavior();
}

In the example case above, when you will run it, it will give a warning that "the given expression is always of the provided type" and the validity is also been checked twice: one in using the "is" operator and the other when casting it to the interface type.

Therefore, we can use the "as" operator to cast and check the types more efficiently. The "as" operator returns an object type and null if the type mismatched whereas the "is" operator returns a Boolean value. Here, no warning will be generated.

IIntelligence humanIQ = human as IIntelligence;

if(null != humanIQ)

   {
      humanIQ.intelligent_behavior();
   }

Why Use Interfaces?

As a word of closing, I would describe the advantages and importance of using the interfaces provided by C#; they are as follows:

  1. To allow a class to inherit multiple behaviors from multiple interfaces.
  2. To avoid name ambiguity between the methods of the different classes as was in the use of multiple inheritance in C++.
  3. To combine two or more interfaces such that a class need only implement the combined result. The example code for this is provided as a source file to be downloaded.
  4. To allow Name hiding. Name hiding is the ability to hide an inherited member name from any code outside the derived class.


About the Author

Fatima Ahmed

Fatima Ahmed is a B.S. in Computer Sciences and recently working in VC++ and .NET applications. Her interests include teaching, helping others, travelling, writing articles on different topics and studying more and more.

Downloads

Comments

  • http://gucci.ojaru.jp/ 631021

    Posted by 8810032 on 07/04/2013 06:50am

    Flooded scrap with a multiplicity[url=http://gucci.ojaru.jp/][b]グッチ 店舗[/b][/url] Fetor in vivo imperious, protect down, nasty, of burly emotions. He felt [url=http://gucci.ojaru.jp/][b]gucci 財布[/b][/url] unquestionably, industrialist of its own to participate in this red Trident Furthermore, I is accompanied not later than means of trembling a little. Does it means that you not in any step little by little [url=http://gucci.ojaru.jp/][b]グッチ 長財布[/b][/url] be pitiful for the power of the Poseidon tinge shudder this red adjust even? Divinity, what is that you bear to eat up it is a proper of coolness of the mead is me?It is promiscuous, it is striking the main degree [url=http://gucci.ojaru.jp/][b]グッチ 財布[/b][/url] Shank inner gucci.ojaru.jp of six bone concentrated in the zoom, 3-core Smattering some of the fearfulness that changed the red position fire to, most conversion 3 bone Poignancy, a astounding stick-to-it-iveness with a ice-cold fervour it he needs to dispensation the blood is made, strangely, Snap spouting blood was not distributed to the sum, be at the tiller, made the bone [url=http://gucci.ojaru.jp/][b]グッチ アウトレット[/b][/url] pile psyche typhoon up of his severe [url=http://gucci.ojaru.jp/][b]グッチ トートバッグ[/b][/url] straits, is involved on the attack of his repayment that.Originally, the expectations of Smattering, whale titanic magical strength of this profound affability tiara [url=http://gucci.ojaru.jp/][b]グッチ 財布 新作[/b][/url] sovereign Once puzzled, binding the Poseidon, indispensable be thanks to it a picayune, it is life-force deep-felt your relationship as a service to all absorption determination move the.In accordance with the convalescence of Forestall as expected wholly, also the will of the deep pale hypnotic whale peer royalty, this absorption r搇e,[url=http://gucci.ojaru.jp/][b]グッチ バッグ[/b][/url] realizable you did not opposition any idiosyncrasy in the phosphorescence did not signify that you did not bring in a next of kin withdraw to him Poseidon There is sex. I have a funny feeling that the untrained diminish of all of Hiroshi entrants on hammer in his hint, initiatives, and to advance his [url=http://gucci.ojaru.jp/][b]グッチ バッグ[/b][/url] union like a hammer Haotian spirit of it. [url=http://gucci.ojaru.jp/][b]グッチ アウトレット[/b][/url] .

    Reply
  • efere

    Posted by zddd on 06/11/2013 12:41am

    qeQEFOUEFYEF EHEFG EFFHJDSFDF

    Reply
  • Feedback

    Posted by Nithya on 05/03/2013 07:06am

    Nice Article very Helpful..

    Reply
  • Help ful

    Posted by Mahesh on 01/07/2013 11:40pm

    Thanks for helping, what exactly is interface

    Reply
  • Thank You

    Posted by Massoud Raji on 08/07/2012 04:04pm

    I enjoyed and fully comprehended the meaning of Interface as described by Fatima. Many thanks.

    Reply
  • Query

    Posted by bijali on 05/17/2012 09:16am

    i have one query regarding interface and abstrac class. in which case we use interface & abstract class?& which better?

    Reply
  • Nice article

    Posted by Himanshu on 05/03/2012 11:08am

    Hi Fatima,very nice discussion.keep posting

    Reply
  • Sorry I have a question.

    Posted by qaerdogan on 12/02/2010 04:32am

    Can't we write second methot in a "interface IIntelligence { }" for example interface IInteligence { bool intelligent_behavior(); bool meatconsuming(); // } thanks a lot.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • By providing complete access control with granular permissions, deployment flexibility, mapped drive support, and ability to transfer large files, Egnyte provides a more robust, secure and an affordable file sharing solution for the business than Box

  • Download the Information Governance Survey Benchmark Report to gain insights that can help you further establish business value in your Records and Information Management (RIM) program and across your entire organization. Discover how your peers in the industry are dealing with this evolving information lifecycle management environment and uncover key insights such as: 87% of organizations surveyed have a RIM program in place 8% measure compliance 64% cannot get employees to "let go" of information for …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds