|
-
October 17th, 2006, 07:32 AM
#1
General question
Hi Gurus,
Why we creating Interface object instead of class object directly. Any specific reason..
Question : IClasss1 obj = new Class1();
Thanks
-
October 17th, 2006, 08:14 AM
#2
Re: General question
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
Bogdan
If someone helped you then please Rate his post and mark the thread as Resolved
Please improve your messages appearance by using tags [ code] Place your code here [ /code]
-
October 17th, 2006, 08:53 AM
#3
Re: General question
Actually there is no reason at all.
When you write:
Code:
IShape myClass = new Rectangle();
or
Code:
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.
-
October 17th, 2006, 03:35 PM
#4
Re: General question
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:
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
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.
-
October 18th, 2006, 05:15 AM
#5
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|