Oops Basics part 3

21) why have interfaces?

There are often situations in which we need to know that the class implements certain features in order to be able to use a class in a certain way. An example is provided by the foreach loop in C#. In principle, it is possible to use foreach to iterate through a class instance, provided that that class is able to act as if it is a collection. How can the .NET runtime tell whether a class instance represents a collection? It queries the instance to find out whether it implements the System.Collections.IEnumerable interface.
If it does, then the runtime uses the methods on this interface to iterate through the members of the collection. If it doesn’t, then foreach will raise an exception.


A second reason for using interfaces is for interoperability with COM. Before the advent of .NET, COM, and its later versions DCOM and COM+, provided the main way that applications could communicate with each other on the Windows platform, and the particular object model that COM used was heavily dependent on interfaces. Indeed, it was through COM that the concept of an interface first became commonly known.

However, that C# interfaces are not the same as COM interfaces. COM interfaces have very strict requirements, such as that they must use GUIDs as identifiers, which are not necessarily present in C# interfaces. However, using attributes, it is possible to dress up a C# interface so it acts like a COM interface, and hence provide compatibility with COM.



22) Construction and Disposal

Most modern OOP languages support the ability to construction and destruction of objects.

This support happens through something called a constructor. A constructor
is a special method called automatically whenever an object of a given class is created. You don’t
have to write a constructor for a class, but if you want some custom initialization to take place automatically, you should place the relevant code in the constructor.

Similarly, A destructor is a method called automatically whenever an object is destroyed (the variable goes out of scope). Reclaiming memory aside, destructors are particularly useful for classes that represent a connection to a database, or an open file, or those that have methods to read from and write to the database/file. In that case, the destructor can be used to make sure that you don’t leave any database connections or file handle hanging open when the object goes out of scope.

23 ) It’s not necessary to provide a constructor for your class, far. In general, if you don’t explicitly supply any constructor, the compiler will just make up a default one for you behind the scenes. It’ll be a very basic constructor that just initializes all the member fields to their normal default values (empty string for strings, zero for numeric data types, and false for bools).

No comments:

Post a Comment