Tuesday, December 4, 2012

Usage of Interfaces in .NET

Interfaces does not have a implementation it only contains the declaration of events, indexers, methods and/or properties. The inherited classes or structs provide the implementation for each of those declarations in the interface.

An interface is a contract between itself and any class that implements it. This contract states that any class that implements the interface will implement the interface's properties, methods and/or events.
One importance of having interfaces is you can have many implementations for same events, indexers, methods and/or properties.

You are referring to the interface in your presentation layer and you can change the implementation of the methods without much changes in your presentation layer.

Another importance is information hiding, suppose that you do want to share the method implementation with other developers then you can present them a interface which shows them only the method declaration. 

Interfaces are very logical way of grouping objects in terms of behavior.
See below example

//Iuser interface has three methods declared.

public interface Iuser
    string Read();
    string Write();
    string Execute();


//UserPermissions class inherits the Iuser interface and implement the interface members

public class UserPermissions:Iuser
    public string Read()
        return "User Can Read";
    public string Write()
        return "User Can Write";

    public string Execute()
        return "User Can Execute";

protected void Page_Load(object sender, EventArgs e)


    private void InterfaceTest()
        Iuser user = new UserPermissions();

        Response.Write(user.Write() + "<br/>");
        Response.Write(user.Execute() + "<br/>");

User Can Read
User Can Write
User Can Execute

No comments:
Write comments
Recommended Posts × +