Understanding Interfaces in C#
 
Published: 06 Dec 2007
Abstract
Interfaces are a very useful tool built into C#. In this article Brendan explains the basics of how interfaces work and for what they may be used. He explains how to create simple custom interfaces and how to implement them.
by Brendan Enrick
Feedback
Average Rating: 
Views (Total / Last 10 Days): 70557/ 178

Introduction

What Interfaces Are

Interfaces basically define a blueprint for a class or a struct. The programmed definition of an interface looks very similar to a class, but nothing is implemented. Interfaces define the properties, methods, events, and indexers, but the interface does not define the implementation of any of these. It just declares their existence. Interfaces will not actually define any functionality. They just define ways in which interactions with a class takes place.

What Interfaces Are Not

Interfaces should not be confused with inheritance. They are two very different things. Inheritance will define a lot of the implementation and is used for code reuse. Interfaces are merely a definition for how communication with the implementing classes must take place. It is like a written contract. A class "signing" the contract will agree to perform certain specified actions in any way it wishes, but it must perform the specified actions.

When to Use Interfaces

Interfaces allow us to create nice layouts for what a class is going to implement. Because of the guarantee the interface gives us, when many components use the same interface it allows us to easily interchange one component for another which is using the same interface. Dynamic programs begin to form easily from this.

Creating an Interface

There are times when you will want to define your own interface. When this situation arises you are probably trying to architect software in such a way as to allow change easily later on. Interfaces are a great tool for scaling software projects. When you define an interface it is done similarly to a class. You give it a name and the contents of the interface are between two curly braces. The contents will be methods, properties, events, and indexers. These components are what the interface is requiring be included in any classes implementing the interface.

Listing 1: IHelloWorlder Definition

interface IHelloWorlder
{
  void SayHello();
  void SayGoodBye();
} 

As you can see I have not actually defined any functionality here. All I have done is said what functionality a class using this interface needs to implement. You'll want to note the name I've used here. It is common practice to prefix interface names with an I. Some examples of this practice can be seem with the following interfaces; IDisposable, IDataReader, and IEnumerable. I am sure everyone reading this has used at least one of the interfaces without knowing it. There are plenty of commonly used classes which implement these interfaces.

Implementing an Interface

Now that we know how to create an interface we will look at how to implement one for a class we write. We could implement an existing interface or one which we have created.

In order to say that we will be implementing an interface in our class we only need to specify it on the same line as our class name following a colon ":" symbol. It looks exactly the same as if we were inheriting from a class.

Listing 2: Implementing an Interface

public class MyHelloWorld : IHelloWorlder
{
}

Since we have defined two methods in our IHelloWorlder interface we will need to make sure that we define these two methods in our class. This is part of the agreement we make with the interface when we define a class. We agree to implement anything it says to implement. This lets our new class act in a similar fashion to the other classes using the interface. If we do not define these methods, Visual Studio will give us a message like this one.

Figure 1

As you can see Visual Studio is requiring that we define these two methods that we agreed to implement when we specified our interface. It is at this point that we will go ahead and write implementations for these two methods we agreed to implement. As you can see because interfaces require certain components of the class to exist it makes it so that different classes may be used interchangeably.

Listing 3: Defining the Methods

public class MyHelloWorld : IHelloWorlder
{
    public void SayHello()
    {
        Console.WriteLine("Hello world!");
    }
 
    public void SayGoodBye()
    {
        Console.WriteLine("Good Bye World!");
    }
}

Now that we have defined the two methods of the interface, Visual Studio will allow us to build successfully. We now have a working implementation of the IHelloWorlder class. We can now take a look at how we will use this interface in our program.

Using Interfaces

Now that we have an interface implemented we can take a look at how we can actually use this interface. One nice thing we can do now when writing a method which will just be calling our interface's methods is that we can have it take the interface instead of the class. Observe the following example.

Listing 4: Using an Interface as a Parameter

public void GreetEveryone(IHelloWorlder hw)
{
    // Perform whatever logic you wish here
    hw.SayHello();
}
 
public void DoSomething()
{
    MyHelloWorld helloWorld = new MyHelloWorld();
    GreetEveryone(helloWorld);
}

If we were to write another class implementing the IHelloWorlder we could alter the DoSomethingMethod and change it to use the new class. Since we just specified the interface in the GreetEveryone method we will not have to change anything in there. A good example of when this type of scaling might occur can be seen with the IDataReader interface.

As an example, pretend that we have a web site and that the web site uses XML files to store all of its data. We use an XmlDataReader to read all of the data from the XML files. Since we have used IDataReader in the program instead of always specifying XmlDataReader everywhere, we can easily change to using a database later. We would be able to change to using a SqlDataReader for example. We will have less code to change because we are using the IDataReader interface and both classes implement it so a lot of the interaction remains the same. If we were to then decide we wanted a different type of database we could easily switch to another IDataReader-implementing class and continue working.

Conclusion

We are able to write these interfaces which are basically just a blue print or a contract defining how interaction will take place with certain classes. Implementing an interface is as easy as fleshing out a class by defining the specified methods, properties, events, and indexers. When we want to use an interface in our code we just define it as if it was a class name, and then we use any class which implements the interface as if it were the interface. By using interfaces we make our code much more maintainable and more dynamic.

Author's Blog

Brendan Enrick



User Comments

Title: Interface   
Name: karthik
Date: 1/16/2013 3:23:31 AM
Comment:
yeah...good...
Title: Interface   
Name: Garv
Date: 12/29/2012 1:32:17 AM
Comment:
Very Right explanation.As a beginner i am expecting a usage of interfaces in window form apllications, web form etc.

Lets say i have to make a customer form so how should i use interface in a proper way

Regards
Garv Singh Rana
Title: Interface   
Name: Bhanu
Date: 12/14/2012 9:09:17 AM
Comment:
yeah...your given description is very effective for a beginners...good going keep it up...
Title: Surajit   
Name: Surajit
Date: 11/28/2012 6:39:25 AM
Comment:
hiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
Title: Anil   
Name: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Date: 11/28/2012 4:44:10 AM
Comment:
rtttttttttttttt
Title: rft   
Name: ret
Date: 11/28/2012 4:43:23 AM
Comment:
rtttttttttttttt
Title: Nice article   
Name: Bond
Date: 9/9/2012 2:10:14 AM
Comment:
can we write examples of interface
Title: RE: Good article but still very less information about function datatypes.   
Name: Brendan Enrick
Date: 7/25/2012 10:10:28 AM
Comment:
Hi Shital,

Thanks for the question. No, you cannot define access modifiers for interface methods.
Title: Good article but still very less information about function datatypes.   
Name: shital
Date: 7/25/2012 3:56:00 AM
Comment:
Can we write protected or internal method declaration in interface?
Title: Good definition   
Name: Durkha
Date: 6/15/2012 1:32:48 AM
Comment:
Very nice explanation of Interface.
Title: Simple and Nice to understand for any one   
Name: suresh
Date: 11/26/2011 1:06:36 AM
Comment:
Nice means of getting understand what interfae is for beignners
Title: Very well explained   
Name: Michael Harper
Date: 8/9/2011 4:20:13 PM
Comment:
I've been struggling with the concept of interfaces even after reading a chapter in my C# book that covers them in depth. This article got through to me what they are actually used for and how they can make applications "Plug and play" so to speak!

Thanks
Title: simplified   
Name: Kuldip
Date: 5/11/2011 9:18:14 AM
Comment:
Excellent Article.
Very Good explanation of interface
Title: Good Defination   
Name: Sarwan
Date: 3/2/2011 11:19:55 AM
Comment:
Hi,
Its really helpful for me.... and once again thanks to you.
Title: Good Definition   
Name: Santosh Joshi
Date: 2/15/2011 7:38:04 AM
Comment:
This helped a lot.
Title: good answer   
Name: javed khan
Date: 1/21/2011 3:53:52 AM
Comment:
hi.....
thanks u for its.
Title: fantastic explanation   
Name: Paul P
Date: 1/19/2011 3:44:05 PM
Comment:
Thanks - I've been agonising over interfaces.... Now finally the penny has dropped and the light at the end of the tunnel is definately back on.

Thanks again - outstanding explanation.
Title: Interfaces   
Name: Manohar
Date: 12/21/2010 2:48:35 AM
Comment:
Good
Title: Good fundamental material   
Name: SK Srivastava
Date: 12/6/2010 8:11:01 AM
Comment:
Fundamentals of interface would be clear.
Title: Nice Article   
Name: David
Date: 9/30/2010 4:34:35 AM
Comment:
Nice Article. What are the advantages of interface.
Title: Good start   
Name: Kiran
Date: 9/22/2010 7:27:32 AM
Comment:
nice article.
Title: Comprehensible   
Name: gets the beginner onboard
Date: 9/13/2010 1:24:21 AM
Comment:
You have to go over it a few times, but it becomes clearer each time you do. Other articles seem clear at first, some even tell you "it's very simple"..but the more you go over them the worse the comprehension. This article excludes everything unnecessary but does not make you deduce anything in order to comprehend. I hate it when I'm learning and have to use stop and use deductive energy before I have gained comprehension. Kudos
Title: Excellent Article   
Name: Excellent
Date: 8/19/2010 8:52:17 PM
Comment:
Excellent writer who writes smooth and easy to follow article. Thanks
Title: Infterface   
Name: Very Good
Date: 8/19/2010 10:18:07 AM
Comment:
Very Good explanation of interface.Smooth English and
good working program codes.
Title: Very Nice   
Name: Gajendra Paliwal
Date: 7/22/2010 2:39:16 AM
Comment:
Thanks ,such a good explanation
Title: Very Good Explanation   
Name: Sam
Date: 7/19/2010 2:39:53 PM
Comment:
thanks allot for such a good explanation - never read on any site - keep posting good articles like this one - but need simple as well as some complex examples also.
Title: Interfaces   
Name: Ana
Date: 4/28/2010 3:07:06 PM
Comment:
Thank you so much for taking your time in posting this excellent article.
Title: Good explanations   
Name: James B Nelson
Date: 4/21/2010 5:28:42 AM
Comment:
Very nice article. I was beginning to understand what an interface was from various google searches, but had no idea why I would care about them until your "using interfaces" section, which is missing from most discussions. It seems to be a very powerful tool that I would have overlooked or dismissed without your article!
Title: Interface   
Name: Prashanth
Date: 3/29/2010 5:58:06 AM
Comment:
Great Article.Its thhe besi have ever seen.Very very helpful for beginners.
Title: Interface   
Name: Bipin
Date: 3/12/2010 8:32:05 AM
Comment:
Great Article.I am very confuse in Interface and Abstract class but when i read this article then my confusion is clear.
Title: interfaces   
Name: roberto
Date: 2/11/2010 9:14:36 PM
Comment:
You lost me with "Using Interfaces". This appears to be a great way to confuse a developer. c# is a nightmare.
Title: Great Article   
Name: Duff
Date: 2/9/2010 10:40:10 AM
Comment:
Great Article! Very easy to follow and understand the reason for using Interfaces. Great Work! Keep it up!
Title: Very Precise and easily apprehended   
Name: BSM
Date: 1/9/2010 1:26:57 AM
Comment:
I have understood the interface concept very easily with this article. Good work
Title: Vey good article   
Name: KCH
Date: 1/3/2010 3:20:51 PM
Comment:
excellent......
Title: Excellant   
Name: GLT
Date: 1/2/2010 9:11:05 PM
Comment:
Best definition of an interface I have ever seen!!!
Title: Great start...   
Name: David
Date: 11/24/2009 4:11:17 PM
Comment:
My only complaint - it's too short. A great start, though and I've already learned enough from the article to search for more advanced materials...
Title: Greatness   
Name: joe
Date: 8/26/2009 3:00:21 PM
Comment:
Thanks for the easy to understand definition as to what Interfaces are good for. I've been reading up on them and no where have I found such a simple explanation of when it is beneficial to use interfaces. Thanks!
Title: Nice Article   
Name: Shashi
Date: 8/21/2009 12:52:12 AM
Comment:
looks good,very simple and to the point. Excellent for beginners
Title: Great Article......   
Name: Ashwin
Date: 7/31/2009 5:43:23 AM
Comment:
What more can a beginner like me ask for.......??
excellent......
Title: Or just maybe...   
Name: mck
Date: 6/20/2009 9:46:32 AM
Comment:
I think there might be a glimmer of light. I`ll need to do a bit more reading to make sure.
Title: Nope   
Name: mck
Date: 6/19/2009 12:19:15 PM
Comment:
Still a total blank for me I`m afraid. Got the example up and running and I just can`t see what the point or benefits
of using the interface is. I`ve never come across anything in programming thats has left me totally bewildered as interfaces have. Its a black hole for me.
Title: Great Article   
Name: Srini
Date: 6/6/2009 10:49:08 AM
Comment:
I've been trying to understand interfaces from many days. This is the best one I came across.

Great Job.

S
Title: thanku   
Name: Sharique
Date: 6/2/2009 4:12:41 PM
Comment:
nice article,,
shariqpk@hotmail.com
Title: Execellent Article on Interfaces   
Name: Nithya Mohanrajh
Date: 4/27/2009 12:17:02 AM
Comment:
Nice article on Interfaces.
Made Understanding very easy with simple and neat explanation.Thanks for the Good work & GoodLuck.
Title: Nice   
Name: Kavita
Date: 3/31/2009 2:28:38 AM
Comment:
Great article. I had read so many article to understand this..but this was the best one.. keep it up.
Title: Thank You   
Name: CLCJR
Date: 3/18/2009 3:16:28 PM
Comment:
Great article keep up the good work... This has really helped.
Title: Thank You!   
Name: suji
Date: 1/20/2009 5:25:21 AM
Comment:
Very good article.Easy to grasp in a very short time.
apprecitae you in taking time in presenting such a good article.short and crisp.
Title: thanku   
Name: sania
Date: 10/22/2008 1:21:09 AM
Comment:
Very good article.Easy to grasp in a very short time.
apprecitae you in taking time in presenting such a good article.short and crisp.
Title: thanks:aspalliance   
Name: senthil kumar
Date: 8/29/2008 5:36:41 AM
Comment:
i understand the use of interface by aspalliance interface.
Title: Can add more to interface   
Name: Imtiaz Mohammed
Date: 7/31/2008 8:46:00 AM
Comment:
Thanks for the information on Interface.It would be great if some more example with more complexity can be added.As the usage of Interface is high while designing classes and interfaces,add more info...Overall it was good knowledge piece.
Title: Thank You!   
Name: Rich
Date: 7/25/2008 5:02:08 PM
Comment:
Sweet and Short to give me a high level understanding of Interfaces. It's articles like these that make things clear and are not congested with complex code to make the author feel smart!
Again , Great Job and thanks for clearing things up on this subject.
Title: Great effort.   
Name: Atul Kumar
Date: 6/13/2008 10:14:40 PM
Comment:
Excellent clarification of the concept.
Title: Feedback   
Name: Brendan Enrick
Date: 5/28/2008 10:00:02 AM
Comment:
@DHIVYAA Well, I am sorry you feel that way. I've tried to write an article which would be easy for people to understand and grasp the concept of an interface. Perhaps you could let me know what it is that you do not like, and I could make an attempt at improving the quality of the article.
Title: Just reviewing   
Name: Dale
Date: 5/21/2008 1:54:23 PM
Comment:
I'm trying to swallow all the .Net now that I have finally made the switch. I read, read, and then short articles like you made, turn the light on for me. I can see !
Title: interface   
Name: zahir
Date: 4/10/2008 6:28:50 AM
Comment:
No at all great but some what ok
Title: interface   
Name: bala
Date: 3/19/2008 6:50:33 AM
Comment:
No at all great but some what ok
Title: Interfaces   
Name: santosh kumar patro
Date: 3/16/2008 11:08:27 AM
Comment:
Thnx very much sir for your help regarding Interfaces.
Title: this.title.new   
Name: this.user.next
Date: 2/29/2008 3:51:43 AM
Comment:
Why the need for all those small parts? It all could have been one whole part.. it irritates me to see all those parts and that too so small??
Title: Excellent Article   
Name: Manpreet
Date: 2/22/2008 3:38:03 AM
Comment:
Excellent article..keep up the good work.
Title: Great job   
Name: George
Date: 2/18/2008 12:57:35 AM
Comment:
its a great interface document
a guy like me know now how to use interfaces
thanks
Title: interface   
Name: chaitu
Date: 1/22/2008 4:23:52 AM
Comment:
it is very help full
Title: Very good explanation, please provide more like this !!!   
Name: Stefan
Date: 1/16/2008 3:47:00 AM
Comment:
It was really a pleasure for me to read this. Not many people are able to explain it that understandable like you did! And it's quite often the most basic things that are confusing if not understood completely.
To those who criticised: be honest and admit that somtimes there's something like this which enlights your priggish minds ;-)
Title: excellent   
Name: Amit
Date: 1/2/2008 2:06:51 AM
Comment:
It is very help full.
Title: very good article   
Name: Mohsen
Date: 12/28/2007 4:38:40 PM
Comment:
yes you've made it very easy understandable ,, thank you
Title: Very informative   
Name: Farrukh
Date: 12/22/2007 2:25:23 AM
Comment:
Yes, you have defined it in a much better and easy and a friendly way.

I was never clear even about its definition by ready books.

Thanks
Title: Interface   
Name: Arvind Gupta
Date: 12/21/2007 10:14:14 AM
Comment:
Very UseFull !
sr_arvind@yahoo.com
Title: Static Methods   
Name: Brendan
Date: 12/13/2007 9:50:33 AM
Comment:
You can read some more about this on my blog post where I talk about this and go int more details about the topic.

http://aspadvice.com/blogs/name/archive/2007/12/13/Static-Methods-and-Interfaces-in-C_2300_.aspx
Title: Static Methods   
Name: Brendan
Date: 12/13/2007 8:55:20 AM
Comment:
Jan,

One important thing to understand about static methods is that they don't really need to be tied to classes. Static methods basically just exist for convenience.

An interface is as the name says an interface to something. Think of it like an automobile interface. There are defined ways of working with the car. They have a steering wheel a gas pedal and brakes. An interface defines that and all automobiles will have those, but an interface doesn't define anything about "cars in general" (static) it defines what will be the interface for individual cars (instances).

I hope that makes sense,
Brendan
Title: what about static functions?   
Name: Jan
Date: 12/13/2007 7:32:28 AM
Comment:
All my classes implementing my interface should have a static funtion.

Why can't I have a static function in an interface???
Title: It finally sinks in   
Name: acousticsatellite
Date: 12/11/2007 10:27:56 AM
Comment:
I have read several articles on Interfaces. Finally I understand their usage. The portion on swapping out the DataReader is what made things click.
Title: Refreshingly well written   
Name: foton
Date: 12/7/2007 12:53:23 PM
Comment:
It's nice to read an article in which the author writes clearly and well. Nice job. I hope others will follow your example.
Title: Designed for beginners   
Name: Brendan
Date: 12/7/2007 9:05:25 AM
Comment:
Yes, I designed this article to be for beginners. I'll be writing more advanced articles on this same topic later.
Title: Useful link for naive users   
Name: Uday D
Date: 12/7/2007 12:31:08 AM
Comment:
Helpful for naive C# programmers. Should have taken a better example.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 9/2/2014 7:40:55 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search