Translate

Monday, July 16, 2012

c# Interface tutorial


Most of the interfaces you come across are a collection of method and property signatures. It can also have signatures of events or indexers.

Example of an Interface


using System;

namespace ConsoleApplication
{
    public interface IPrinter
    {
        void Print();

    }
}

Any one who implements an interface must provide definitions to what ever is in the interface. For example, any class that implements the IPrinter interface must implement a Print Method. For example


using System;

namespace ConsoleApplication
{

    class Program
    {
        static void Main(string[] args)
        {
            DilbertsPrinter prn = new DilbertsPrinter();
            prn.Print();            
        }

    }

    public class DilbertsPrinter:IPrinter
    {
        public void Print()
        {
            Console.WriteLine("My Printer");
        }
    }
}



You cannot instantiate an interface, but you can set a variable of an Interface type to a class that implements that interface. For example I can do this,


IPrinter printer1 = new DilbertsPrinter();
printer1.Print();

The  printer1.Print() will call the print method on the class DilbertsPrinter. Through the interface variable  printer1, if you try calling a method on the class  DilbertsPrinter, which is not a part of the interface IPrinter, it will throw a compile time error.

This is a very important property, which is extensively used when applying the programming to an interface design principle.


 A few points to note about an interface:

  • An interface can only have signatures of methods, properties, events and indexers. Trying to add fields or anything else will throw compile time errors.
  • A class can implement more than one interface.
  • An interface itself can inherit from multiple interfaces.
  • You cannot add access modifiers (public, private etc) to the members of an interface. All the  members of an interface are by default public. 
  • The interface itself (not its members) can have all the modifiers (private,public etc) if it is defined inside a class. If it is defined in a namespace, it can only be public. (Most interfaces are defined inside a namespace and not a class.)

Further reading:
http://msdn.microsoft.com/en-us/library/ms173156(v=vs.110).aspx

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator