Hi Gurus,
Why we creating Interface object instead of class object directly. Any specific reason..
Question : IClasss1 obj = new Class1();
Thanks
Printable View
Hi Gurus,
Why we creating Interface object instead of class object directly. Any specific reason..
Question : IClasss1 obj = new Class1();
Thanks
An interface is nothing more than a named collection of semantically related abstract members. The specific members defined by an interface depend on the exact behavior it is modeling. It is common to regard an interface as a behavior that may be supported by a given type. When more classes implement the same interface you can treat them the same way ( also known as interface-based polymorphism).
http://msdn2.microsoft.com/en-us/library/ms173156.aspx
http://www.developer.com/net/csharp/article.php/1482651
http://www.csharphelp.com/archives/archive171.html
Actually there is no reason at all.
When you write:
orCode:IShape myClass = new Rectangle();
these are exactly the same.Code:Rectangle myClass = new Rectangle();
The only differences I can think of are:
1. intellisense: In the first one you cannot call any member of the class that does not belong to the interface (so it's easier to filter the methods and properties)
2. When passing to methods that expect the type of the interface you don't need to cast.
AFAIK you don't have to cast when passing an object of a class that implements a given interface to a method that requires an object of that interface.
One reason would be to do something like this:
Another would be clarity of code, or possibility to change implementation, e.g. we could use IList, and choose from any collection that implements IList, maybe we start with one that is efficient for small collections but then need to change to another that is efficient for larger collections or sorted collection or whatever.Code:IMyInterface x=new MyClass1();
// do something with x
if (someConditionIsTrue)
x=new MyClass2();
// continue doing something with x, which now may or may not refer to another object, we don't care as long it has the same interface
Thanks for the reply .