Solved

Question on polymorphism in C#

Posted on 2011-09-10
8
203 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
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 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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.

623 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