jump to navigation

Polymorphism in C# (from C++) May 17, 2006

Posted by codinglifestyle in C#.
Tags: , , , , ,
trackback

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.

Advertisements

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: