Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Question on polymorphism in C#

Posted on 2011-09-10
8
Medium Priority
?
225 Views
Last Modified: 2013-12-17
hello group,

In my code, I forgot to use virtual keyword in the base class and also skipped using override keyword before a method which has to mimic part of its performance from the function with the same name in base class.

However, still the code does what a proper code would do.

can somebody give me some insight into this?

thanks,
ak
0
Comment
Question by:akohan
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 1

Expert Comment

by:ananken
ID: 36517288
No need for virtual in class definition in C#, it is intended for overridable methods.

When compiling look at the warnings - it will suggest that you add the new keyword before your method. The extending class's method will be called in this manner only if you use a reference to that class. If you use a reference to the base class, the base method will be called, while if you had used virtual on the base method and override on the extending method, the extending method would have always been called, regardless of whether the reference you use is of the extending class's type or of the base one.
0
 
LVL 33

Expert Comment

by:Todd Gerbert
ID: 36517324
http://msdn.microsoft.com/en-us/library/435f1dw2%28VS.80%29.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
	static void Main(string[] args)
	{
		Horse mrEd = new Horse();

		TestMethod(mrEd);

		Console.ReadKey();
	}

	static void TestMethod(Equine obj)
	{
		// A "Horse" object is passed in
		// where an "Equine" object was expected,
		// this is allowed by polymorphism since
		// Horse derives from Equine

		// Speak was redefined, not overridden,
		// so we get the base class's "Nay"
		obj.Speak();

		// Sneeze is marked virtual, and overridden
		// in the derived class, so we get the Horse's
		// "Excuse me..."
		obj.Sneeze();
	}
}

class Equine
{
	public void Speak()
	{
		Console.WriteLine("Nay");
	}

	public virtual void Sneeze()
	{
		Console.WriteLine("Hachoo");
	}
}

class Horse : Equine
{
	// If you omit the "new" keyword your code will
	// still compile and run, as if the "new" keyword
	// was present, you'll just get a warning
	new public void Speak()
	{
		Console.WriteLine("Hello, Wilbur!");
	}

	public override void Sneeze()
	{
		// Overriding 
		Console.WriteLine("Excuse me...");
	}
}

Open in new window

0
 

Author Comment

by:akohan
ID: 36517471

Thanks to you both. if I have understood it properly then it means missing virtual/override only causes warning message however, compiler still knows how to deal with it.

Regarding Tgerbert's comment, I'm not sure what you mean by "new" keyword since I'm not doing it as:

new public void Speak()
{
            Console.WriteLine("Hello, Wilbur!");
}

this is my case:

in base class:

public /*virtual*/ void DrawWindow() {}

and in extended class:

public /*override*/ void DrawWindow()
{

   base.DrawWindow();  //invoke the base method

}
0
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 36517772
When you have a derived class which defines a method of the same name as a function in the base class, but you are not overriding the base class implementation, you should use the new keyword to denote that you intended to hide the base class implementation, not override it. Typically, there is not much call for method hiding, but I believe if you do not include the new keyword on the derived class' method, the compiler will do it for you. I believe it warns you and request that you include the keyword as a reminder, in case you meant to override, but forgot to.
0
 

Author Comment

by:akohan
ID: 36519756

Thank you for your time. I cannot digest this ... so override means that I am replacing the old method in base class. Right?

Also, new means that I'm writing a new method which would replace the base class method again.  Now, my final question would be "what is the difference then?"


Regards,
ak
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 400 total points
ID: 36524665
Try this link out. I think it explains the difference better than I ever could:

    http://msdn.microsoft.com/en-us/library/ms173153%28v=vs.80%29.aspx
0
 
LVL 33

Assisted Solution

by:Todd Gerbert
Todd Gerbert earned 200 total points
ID: 36536527
override means you are extending the base class - where the base class was written with the virtual keyword, indicating that you are welcome to extend it in a derived class.

new means you are deliberately adding a new method to your derived class with the same name as a method that already exists in the base class. You will almost never do this in routine programming.  The compiler warning is way to Visual Studio to say:

"Hey dummy, you gave a method in your class the same name as a method in the base class - are you sure you want to do that? If so, use the new keyword so I know you meant to do that; otherwise change the name of your method so it doesn't conflict with the base class."

The behavior of the two approaches varies slightly - see the code snippet I posted above, http:#a36517324 (read the comments in the code snippet).  Basically (and this is somewhat of an over-simplification) don't re-write methods in derived classes unless that method in the base class is marked virtual and you use the override keyword in your derived class.
0
 

Author Comment

by:akohan
ID: 36915343

Thanks!!!
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…
Suggested Courses

927 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question