Working with Interfaces in C#


This article was contributed by Anand Narayanaswamy.

Environment: .NET and C#

In this article, you will learn about the concept behind interfaces in C# with the help of relevant listings.

Interfaces

To rectify the drawback of multiple inheritance, the creators of C# have introduced a new concept called interfaces. Java programmers may be well aware of this concept. All interfaces should be declared with the keyword interface. You can implement any number of interfaces in a single derived class, but you should provide signatures to all method definitions of the corresponding interfaces. To illustrate, Listing 1 shows how to declare interfaces and implement them in a class:

Listing 1

using System;

interface Interdemo
{
  void Show();
}

class Interimp:Interdemo
{
  public void Show()
  {
    Console.WriteLine("Show() method Implemented");
  }

  public static void Main(string[] args)
  {
    Interimp inter = new Interimp();
    inter.Show();
  }
}

Combining Interfaces

Two or more interfaces can be combined into a single interface and implemented in a class, as shown in Listing 2:

Listing 2

using System;
interface Interdemo
{
  void Show();
}

interface Interdemo1
{
  void Display();
}

interface Combineinter:Interdemo,Interdemo1
{
  //Above interfaces combined
}

class Multipleinterimp:Combineinter
{
  public void Show()
  {
    Console.WriteLine("Show() method Implemented");
  }

  public void Display()
  {
    Console.WriteLine("Display() method Implemented");
  }

  public static void Main(string[] args)
  {
    Multipleinterimp inter = new Multipleinterimp();
    inter.Show();
    inter.Display();
  }
}

You easily can determine whether a particular interface is implemented in a class by using is and as operators. The is operator enables you to check whether one type or class is compatible with another type or class; it returns a Boolean value. Listing 3 illustrates the usage of the is operator by revisiting Listing 2.

Listing 3

using System;

interface Interdemo
{
  bool Show();
}

interface Interdemo1
{
  bool Display();
}

class Interimp:Interdemo
{
  public bool Show()
  {
    Console.WriteLine("Show() method Implemented");
  return true;
  }

  public static void Main(string[] args)
  {
    Interimp inter = new Interimp();
    inter.Show();

    if(inter is Interdemo1)
    {
      Interdemo1 id = (Interdemo1)inter;
      bool ok = id.Display();
      Console.WriteLine("Method Implemented");
    }

    else
    {
      Console.WriteLine("Method not implemented");
    }
  }
}

Whereas the is operator returns a boolean value as shown in the preceding listing, the as operator returns null if there is any incompatibility between types. Listing 4 examines the usage of this operator. Here we have revisited Listing 3. Notice the change in code inside the Main () method.

Listing 4

using System;

interface Interdemo
{
  bool Show();
}

interface Interdemo1
{
  bool Display();
}

class Interimpas:Interdemo
{
  public bool Show()
  {
    Console.WriteLine("Show() method Implemented");
    return true;
  }

  public static void Main(string[] args)
  {
    Interimpas inter = new Interimpas();
    inter.Show();

    Interdemo1 id = inter as Interdemo1;

    if(null!=id)
    {

      bool ok = id.Display();
      Console.WriteLine("Method Implemented");
    }

    else
    {
      Console.WriteLine("Method not implemented");
    }
  }
}

Avoiding Name Ambiguity

Suppose you are declaring same method definitions in two different interfaces. The compiler will naturally show an error due to the ambiguity of the implemented method. Even if you use the "is" keyword, the compiler still will show warnings. To avoid this, you have to follow the syntax as shown in Listing 5:

Listing 5

Void <interface name>.<method name>
{
  //Body goes here
}

Listing 6 illustrates the application of the preceding concept in detail:

Listing 6

using System;

interface Interdemo
{
  void Show();
}

interface Interdemo1
{
  void Show();
}


class Interclash:Interdemo,Interdemo1
{
  void Interdemo.Show()
  {
    Console.WriteLine("Show() method Implemented");
  }

  void Interdemo1.Show()
  {
    Console.WriteLine("Display() method Implemented");
  }

  public static void Main(string[] args)
  {
    Interclash inter = new Interclash();
    inter.Interdemo.Show();
    inter.Interdemo1.Show();
  }
}

About the Author

Anand Narayanaswamy works as a freelance Web/Software developer and technical writer. He runs and maintains learnxpress.com, and provides free technical support to users. His areas of interest include Web development, Software development using Visual Basic, and in the design and preparation of courseware, technical articles, and tutorials.



About the Author

Anand Narayanaswamy

Anand Narayanaswamy (Microsoft MVP) is a freelance writer for Developer.com and Codeguru.com. He works as an independent consultant and runs NetAns Technologies (http://www.netans.com)which provides affordable web hosting services. He is the author of Community Server Quickly (http://www.packtpub.com/community-server/book). Anand also runs LearnXpress.com (http://www.learnXpress.com) and Dotnetalbum.com (http://www.dotnetalbum.com) and regularly contributes product and book reviews for various websites. He can be reached at ananddotnet@yahoo.co.in

Comments

  • C# code

    Posted by giriyasama on 03/11/2010 08:30am

    i need c# code to retrieve data from USB device...can u help?

    Reply
  • Where are you go.

    Posted by Legacy on 10/19/2002 12:00am

    Originally posted by: JongHwan Kim

    ....

    Reply
  • Very Helpful

    Posted by Legacy on 10/18/2002 12:00am

    Originally posted by: Nauman Ahmed

    Thanks anand this solved my problem with interfaces... thanks again....

    Nauman Ahmed...

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

Top White Papers and Webcasts

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

  • Live Event Date: September 16, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you starting an on-premise-to-cloud data migration project? Have you thought about how much space you might need for your online platform or how to handle data that might be related to users who no longer exist? If these questions or any other concerns have been plaguing you about your migration project, check out this eSeminar. Join our speakers Betsy Bilhorn, VP, Product Management at Scribe, Mike Virnig, PowerSucess Manager and Michele …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds