Solved

Question on polymorphism in C#

Posted on 2011-09-10
8
197 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
 
LVL 74

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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

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 74

Accepted Solution

by:
käµfm³d   👽 earned 100 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 50 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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

708 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now