jump to navigation

Interfaces in C# July 22, 2008

Posted by fofo in .NET, asp.net, C#, c# 3.0.
Tags:
trackback

I am currently teaching people from all walks of life about designing and implementing asp.net web applications with .net 3.5 and visual studio 2008. Everyone wants to develop a web application right away. But I keep encouraging them to find out more about the basics of OO. When it comes to the term Interface most novice developers are confused. In this post I will try though a practical example and some definitions to clear things….

So what is actually an interface? I will start with an example from real life. We use interfaces or interface all the time. When my dad told me how to dial my first telephone number from our home phone many years ago, I was pretty pleased. When we visited my uncle in their house I could use their phone just as easy.

Imagine if someone had to teach me all over again how to use the phone. I do not need to know how the interface is implemented for a phone. I can use the buttons in the panel (the interface in this case)  and know that the phone will subscribe to the general phone interface.

Let’s see interface characteristics in the “code world”

  • An iterface defines only the properties and method signatures and not the actual implementation. I mean that in a class declaration we implement fields,properties,methods and events. In an interface we just define what properties/methods the class should have.
  • Requires that classes which implement an interface must “honour” the property and method signatures. Basically are like contracts for classes. Classes which implement an interface must implement the methods and the properties of the interface
  • Many classes can implement a particular interface method, in their own way
  • An interface may inherit from multiple base interfaces
  • A class may implement-inherit from multiple interfaces
  • A C# class may only inherit from one class

Let’s see a simple example

1) Create a asp.net web application with C#

2) Add a new item to your project, a class file, called Human.cs.

3) Let’s define an Interface, called IHuman.

Just above this line of code

public class Human

type the following

 

interface IHuman
{
    void Read();
    void Write(object obj);
    int Height { get; set; }
    int Weight { get; set; }

}

here we define properties and methods that the class that subscribes to this interface must implement.

We prefix the name of the Interface with an “I”. Just a widely accepted convention…

4) Now let’s implement the class

Here we declare (sign a contract so to speak, that the Human class will Implement the IHuman Interface)

public class Human:IHuman

Right after the line above type

private int height;
        private int weight;

    public Human(string s)
         {
             MessageBox.Show(s);
      
         }

         // implement the Read method
         public void Read()
         {
             MessageBox.Show(
                 “Implementing the Read Method for IHuman”);
         }

         // implement the Write method
         public void Write(object o)
         {
             MessageBox.Show(
                 “Implementing the Write Method for IHuman”);
         }
         // implement the property Height
         public int Height
         {
             get { return height; }
             set { height = value; }
         }

// implement the property Weight

public int Weight
         {
             get{ return weight; }
             set{ weight = value; }
         }

As i said before the class must “honour” its contract with the interface.

Before you go on try to comment this code out

public void Read()
    {
        MessageBox.Show(
            “Implementing the Read Method for IHuman”);
    }

Try to build your application. Well as you see from the error message below, someone is not honouring his contract….

Human’ does not implement interface member ‘IHuman.Read()’

5) From our Page_Load event of the defaul.aspx page we can create a new instance of the Human class

 Human myperson = new Human(“fofo”);
        myperson.Read();
        myperson.Weight = 78;
        myperson.Height = 88;
        Response.Write(myperson.Weight);
        Response.Write(“</br>”);
        Response.Write(myperson.Height);

Please note that i could have a Boy class that could implement the IHuman interface.

public class Boy:IHuman

each class (boy,human) should implement the Read method of the IHuman interface. But each class was free to implement it in its own way. 

We could define the IHuman interface above as an abstract class.And then had our class inheriting from our abstract class. But if changed slighlty the implementation of our abstract class then the referencing classes would fail and so our application would fail. If we work with Interfaces and we are commited to follow good practices like, never to alter the Interface implementation after they have been deployed, we will not run into such problems.

Read this article from msdn to see when to use interfaces

Read this article from msdn to see when to use Inheritance

Add to FacebookAdd to NewsvineAdd to DiggAdd to Del.icio.usAdd to StumbleuponAdd to RedditAdd to BlinklistAdd to Ma.gnoliaAdd to TechnoratiAdd to Furl

About these ads

Comments»

1. NM - January 21, 2009

I think interfaces were and are hard for me to understand because I’ve always written bad code. Why would I want to add something new – I already have to do find an replace enough! But the idea here is that these practices help you as a programmer, and without some planning they might not be all that good. If I’m correct – interfaces aren’t something that are just created in 1 minute like in samples, but are representative of a good understanding of the scope and purpose of the application from the get go.. no?

2. fofo - January 21, 2009

yes, you must understan when to use interfaces and when inheritance. also most of the base classes and all the classes in the .net world implement some sort of Interface. for example C# 3.0/LINQ classes implement the IQueryable

3. Bhu - June 9, 2009

Its a very nice article, which clears about my doubt of Interface, which i had never used before.
Thank You

4. Object Oriented Programming Concepts with C#3.0 « DOT NET RULES - June 21, 2009

[...] thing to review is Interfaces. I will not cover Interfaces in detail because you can find another post of mine on Interfaces on this [...]

5. Arjun - January 26, 2010

Hi,
I just understood in interface is if write any methods in it, we need to implement all the methods in the class.
We can write all those methods in a Human class without implementing an interface.
Why to use interface.

6. fofo - January 26, 2010

In an iterface you define only the properties and method signatures and not the actual implementation. Then you are right you have to implement these methods and properties in the classes that subscribe to the interface. With interfaces we are moving away from considering classes in terms of what they are, and starting to think about them in terms of what they can do.Have a look here
http://www.4guysfromrolla.com/articles/110304-1.aspx

hope it helps!!!

7. Ecko - June 15, 2010

nice article, thanks,,

8. Vikram Singh Saini - December 29, 2010

I love your way of explaining hard stuff in simple style.

I owe you my salute for such a excellent nice work.

9. Daniel - February 7, 2011

Hello,
I’m quite confused as your class :public class Human:IHuman
is public, I think it doesn’t goes through the interface but in the class itself;

10. Daniel - February 7, 2011

What I mean is that if you comment inside the interface such as:
interface IHuman
{
void Read();
void Write(object obj);
//int Height { get; set; }
//int Weight { get; set; }
}

You still get your code running, there is no compilation error and in the .aspx page when we pass paramters, we still get the correct values

11. Daniel - February 7, 2011

Finally I made some tests in order to achieve what I had in mind (isolate the business from the interface) I changed this:
5) From our Page_Load event of the defaul.aspx page we can create a new instance of the Human class

Human myperson = new Human(“fofo”);

into :
1. declaring my interface as public (public interface IHuman)
2. in the .aspx page I call it like:
Ihuman myPerson = new Human(“fofo”);

From now, If I comment properties, methods,.. in the interface, they are not reachable in my [MyPerson] object though they are still present in the class itself;
I think that now I’m effectively going through the interface as expected.

12. Sunil - June 9, 2011

Nice Article

13. Deepak Sahu - December 9, 2011

Whenever i try to use your code as given in Ihuman and Human example of Interface.. the editor itself gives error for every MessageBox.show item that [[ Then name "MessageBox" does not exist in the current context]].
Where do i stand corrected please ??

fofo - December 9, 2011

you are probably missing some references. some “using” statement on the top of the file.

Add a reference to the System.Windows.Forms assembly and then add in the top of the file “using System.Windows.Forms;”

siddharth - August 19, 2012

please elaborate how i add this reference…please help

14. heel lift inserts - January 8, 2013

Interfaces in C# DOT NET RULES seems big


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,786 other followers

%d bloggers like this: