Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Question on polymorphism in C#

Posted on 2011-09-10
8
Medium Priority
?
217 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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 
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

 [eBook] Windows Nano Server

Download this FREE eBook and learn all you need to get started with Windows Nano Server, including deployment options, remote management
and troubleshooting tips and tricks

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

715 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