Click to See Complete Forum and Search --> : General question
saiprabhur
October 17th, 2006, 07:32 AM
Hi Gurus,
Why we creating Interface object instead of class object directly. Any specific reason..
Question : IClasss1 obj = new Class1();
Thanks
creatorul
October 17th, 2006, 08:14 AM
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
jhammer
October 17th, 2006, 08:53 AM
Actually there is no reason at all.
When you write:
IShape myClass = new Rectangle();
or
Rectangle myClass = new Rectangle();
these are exactly the same.
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.
klintan
October 17th, 2006, 03:35 PM
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:
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
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.
saiprabhur
October 18th, 2006, 05:15 AM
Thanks for the reply .
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.