Christopher Green

Now with more Vitamin C!
posts - 41, comments - 30, trackbacks - 1

Polymorphism in C# (from C++)

One thing you don't see often enough in C# is the intelligent use of polymorphism. Coming from a C++ background I ground to a halt for 15 minutes to review the differences in order to create a base class with pure virtual functions.

First off, is the difference in the virtual keyword itself. In C++ the base class defines a function as virtual and the derived class can simply redefine the function.  The derived class can optionally make the function virtual or change the access.


class A
{
 public virtual func();
}

class B : A
{
 private func();
}

or

class B : A
{
 public virtual func();
}

In C# you must explicitly use the override keyword in the derived class.  This keyword is a bit more explicit and keeps the function virtual.

Interestingly C# adds another keyword to make a pure virtual function.  Whereas in C++ we can define a pure virtual function like this

class A
{
 public virtual func() = 0;
}

In C# we use the abstract keyword and drop the '= 0'.  Lastly is the use of the sealed keyword.  As is often in case with virtual functions after a couple derivations they become too specialized or too specific to be derived from again.  In this case we can use the sealed keyword to prevent the redefinition of a function or at the class level to prevent inheriting the entire class. 

This handy FAQ and a quick review in my C# book cleared up my C# knowledge gap and got me back to developing a well-written base class.

Print | posted on Wednesday, May 17, 2006 4:23 PM |

Comments have been closed on this topic.

Powered by: