|
.net
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
interfaces in c#.nethello frnds
if any one cud help me how to implement the concept of interface and interface objects in c#.net.
if its not possible to expalin in mail..plz do send me some link where it is best explained
Thanks
--- Posted using Wimdows.net Newsgroups - http://www.wimdows.net/newsgroups/ You might get a better response posting this in a C#-specific group.
However... An interface is a structure that declares certain methods and properties (like a class), but doesn't provide implementations of them. So, you can (almost) never create an instance of an interface with 'new', as it's meaningless - the resulting object can't actually *do* anything. Instead, you define a class that implements the interface - that is, the interface name is included in its list of base classes, and the class is then required by the compiler to implement all of the functions declared in the interface. The idea is that you can then define functions that take as a parameter an object of arbitrary type, but which is known to implement the interface (declaring a variable of interface type means it is a reference to some object of a class implementing the interface); then, you can use the methods that you know must exist in the class (those defined in the interface) to do whatever you want, without concerning yourself with what other methods/functionality the object may have. So, for example, the IEnumerable interface in .NET is implemented by collection classes, and it means that an object of any class implementing it, regardless of how the collection itself actually works, can be used as a 'foreach' variable and a few other things, as the compiler then knows that the object passed is guaranteed to have certain functionality. To define your own interface, use the 'interface' keyword, and declare the members like for a class (but without function bodies). Then, you could have a function that takes as a parameter an object implementing the interface, which could actually be an instance of any class you write that implements the interface. e.g. [syntax may be *slightly* wrong as I haven't tried compiling this]: interface ISortable { void SortData(); bool IsSorted { get; } } class SomethingSortable : ISortable { void SortData() // if we don't override this function our class won't compile { [...] } bool IsSorted { get { return ...; } } } Now we could have a method somewhere like this: object BinarySearch(ISortable lst) { lst.SortData(); // we know this method has to exist in any object passed } Hope that helps... |
|||||||||||||||||||||||