Thursday, July 9, 2009

Can we create instance of Interface in C#?

Hello, I believe your a bit confused about what an Interface is. Let me start giving you a definition about what it really means:





"An Interface is a reference type and it contains only abstract members (Events, Delegates, Methods, Properties and Indexers).The interface only places declarations, the implementation of those declaration should be placed in a class that implements it."





So let us say we have an interface called, Item.


Note that the below is just a small mockup...


http://rafb.net/p/7W3MiQ43.html


=====================================


///


/// Item.cs


///


public interface Item


{


public double CalculatePrice(int zipcode);


public double Price { get; set; }


}





///


/// Beverage


///


public class Beverage : Item


{


public Beverage() { ... }


public double CalculatePrice(int zipcode)


{


...


...


}





public double Price


{


get


{


...


...


}





set


{


...


...


}


}





///


/// Candy


///


public class Candy : Item


{


public Candy() { ... }


public double CalculatePrice(int zipcode)


{


...


...


}





public double Price


{


get


{


...


...


}





set


{


...


...


}


}





///


/// Main Class


///


public main ()


{


Item currItemA = new Candy();


Item currItemB = new Beverage();


}


=====================================





Now notice how I am using it? I am filling up the Interface from instantiating the class that implements it. That is how we create an instance of an Interface.





Usually the way I use interfaces is for loosely coupling classes from each other, so I have multiple packages, And I have one main public class that brings instances the underlying class so the programmer from the other package don't need to worry about the implementing classes, he just sees the Interface and the Main Controller Class.





Very good practice.





I hope I helped a lil.


No comments:

Post a Comment