Sunday, January 31, 2010

Implementation Inheritance

If you want to declare that a class derives from another class, use the following syntax:

class MyDerivedClass : MyBaseClass
{
// functions and data members here
}

Note This syntax is very similar to C++ and Java syntax. However, C++ programmers, who will be used to the concepts of public and private inheritance, should note that C# does not support private inheritance, hence the absence of a public or private qualifier on the base class name. Supporting private inheritance would have complicated the language for very little gain. In practice, private inheritance is used extremely rarely in C++ anyway.


If a class (or a struct) also derives from interfaces, the list of base class and interfaces is separated by commas:

public class MyDerivedClass : MyBaseClass, IInterface1, IInterface2
{
// etc.

For a struct, the syntax is as follows:

public struct MyDerivedStruct : IInterface1, IInterface2
{
// etc.

If you do not specify a base class in a class definition, the C# compiler will assume that System.Object is the base class. Hence, the following two pieces of code yield the same result:

class MyClass : Object // derives from System.Object
{
// etc.
}

and

class MyClass // derives from System.Object
{
// etc.
}

For the sake of simplicity, the second form is more common.

Because C# supports the object keyword, which serves as a pseudonym for the System.Object class, you can also write:

class MyClass : object // derives from System.Object
{
// etc.
}

If you want to reference the Object class, use the object keyword, which is recognized by intelligent editors such as Visual Studio .NET and thus facilitates editing your code.

Regards,
Praveen KVC
31 January 2010

0 comments:

Post a Comment