iEntry 10th Anniversary RSS Newsletter Advertising
Visit Twellow.com
Text: Decrease Font Size Increase Font Size | Print Print Article | Share: Delicious Digg StumbleUpon Post to Twitter Post to Facebook
CommentMonday, August 1, 2005

Virtual Methods & Polymorphism in C#

Virtual methods allow object oriented languages to express polymorphism.This means that a derived class can write a method with the same signature as a method in its base class, and the bas class will call the derived class's method.By default in java, all methods are virtual.

In C# like c++, the virtual keyword is needed to specify that a method should override a method (or implementaion an abstract method) of its base class.

Class B {
public virtual void foo () {}

}
ClassD : B {
public override void foo () {}
}

Attemting to override a non-virtual method will results in a compile-time error unless the "new" keyword is added to the declaration, indicating the method is intentionally hiding the base clas's method.

Class N : D {
public new void foo () {}
}
N n = new N ();n.foo; // calls N's foo ((D)n).foo; // calls D's foo
((B)n).foo(); //calls D's foo

In contrast to both c++ and Java, requiring the override keyword makes it more clear as to what methods are overridden when looking at source code.However, requiring the use of the virtual methods has its pros and cons. The first pro is the slightly increased execution speed from avoiding virtual methods.The second pro is to make clear what methods are intended to be overridden.However, this pro can also be a con.Compare the default option of leaving out a final modifier in Java Vs leaving out a virtual modifier in C++. The default option in Java may make your program slightly less efficient, but in C++ it may prevent extendibility, albeit unforeseen, by the implementer of the base class.

Pawan Bangar, Technical Director, Birbals, #1047,Sector 42-b, Chandigarh. www.ebirbals.com, www.birbals.com

About the author:
Pawan Bangar, Technical Director, Birbals, #1047,Sector 42-b, Chandigarh. www.ebirbals.com, www.birbals.com

Publish A Comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
8 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
SEARCH
Popular WPN Business Resources












Subscribe to WebProNews


Send me relevant info