The override that was not (Popular Misconception) in C#

No.of Views2211
Bookmarked0 times
Downloads 
Votes0
By  j2inet   On  17 Jul 2010 23:07:03
Tag : CSharp , General
The override that was not (Popular Misconception) in C#
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

I was interviewing for jobs this past week and at all of the interviews, I was presented with questions about object oriented techniques and C#. When asked about overriding a method on a class that wasn't marked as virtual, I informed the interviewers that it can't be done. I didn't realize that the interviewers were considering my answer to be wrong until yesterday when an interviewer presented to me the answer that he was looking for. He told me that I could override an otherwise unoverridable method by using the new keyword on it. That started a discussion which resulted in the interviewer wondering whether or not the method was really effectively overridden. After I had the discussion with him, I realized the earlier interviewers may have also thought that my answer was incorrect.

The misconception comes from an observation of what happens when one uses the new keyword on a method. To make this discussion a little more concrete, I'll share some example code.

Code Snippet

class MyBase
{public virtual string MethodA() 
    {return "Hello from MethodA";
    }public string MethodB()
    {return "Hello from MethodB";
    }
}

 What this class does is obvious.It has two methods both of which return a unique string. The class is simple enough that I'm sure you'll trust me when I say it reliably does its job without error. One of the methods is marked as virtual, so it is overridable. The other is not. So now I derive a class from this base class.

Code Snippet

class Derived : MyBase
{public override string MethodA()
    {return "Hello from Derived::MethodA";
    }public new string MethodB()
    {return "Hello from Derived::MethodB";
    }
}

 In this derived class, I have overridden MethodA. Since MethodB is not marked as virtual, I could not override it so I used the new keyword. Let's test the program to see what type of output it produces.

static void Main(string[] args)
{
    var a = new Derived();
    var b = new MyBase();

    Console.Out.WriteLine(b.MethodA());
    Console.Out.WriteLine(b.MethodB());

    Console.Out.WriteLine(a.MethodA());
    Console.Out.WriteLine(a.MethodB());
}

 The output from running this is what one would expect. When I call MethodA and MethodB the strings derived in the derived class are displayed.

Hello from MethodA
Hello from MethodB
Hello from Derived::MethodA
Hello from Derived::MethodB

 Upon seeing this behaviour, it seems that the developers I spoke to last week thought this to be the functional equivalent of overriding. But the difference shows up when the instance of the class is handled through either an interface or a base class reference. Let's say I appended the following to the above code:

var c = a as MyBase;

Console.Out.WriteLine(c.MethodA());
Console.Out.WriteLine(c.MethodB());

 The output is not consistent with what we would expect an overridden method would produce.

Hello from Derived::MethodA
Hello from MethodB

 The above output demonstrates that when a method has been overridden, then the method will be called regardless of the interface used to interact with the object instance. MethodA had been overridden so even though a variable whose type is of the base class is used, the overridden implementation is invoked. MethodB was never truly overridden so when a base class reference is used, the base class implementation is called.

So then what did the new keyword really do? It allowed some one to create a method that has the same signature and name as an existing method. While the method is called with the same notation that would have been used to call the original method, it is not actually performing an override. It is only hiding it. For confirmation, one can also look at the C# documentation for the new keyword on MSDN which refers to this as name hiding. http://msdn.microsoft.com/en-us/library/51y09td4(VS.71).aspx#vclrfnew_newmodifier

Name hiding through inheritance takes one of the following forms:

A constant, field, property, or type introduced in a class or struct hides all base class members with the same name.
A method introduced in a class or struct hides properties, fields, and types, with the same name, in the base class. It also hides all base class methods with the same signature. For more information, see 3.6 Signatures and overloading.
An indexer introduced in a class or struct hides all base class indexers with the same signature.

Digging deeper into the documentation, we find the following:

The scope of an entity typically encompasses more program text than the declaration space of the entity. In particular, the scope of an entity may include declarations that introduce new declaration spaces containing entities of the same name. Such declarations cause the original entity to become hidden. Conversely, an entity is said to be visible when it is not hidden.

Conclusion

The new keyword is not performing an override, it is a scoping operator.

 
Sign Up to vote for this article
 
About Author
 
j2inet
Occupation-Not Provided
Company-Not Provided
Member Type-Senior
Location-Not Provided
Joined date-12 Jun 2009
Home Page-Not Provided
Blog Page-Not Provided
 
 
Other popularSectionarticles
    I can see, there is lots of people is discussing about it in MSDN forums, few people wanted to get rid of the Task from the async methods and really want to deal with normal return types, while others just wanted to get rid of the async postfix
    Published Date : 25/Nov/2010
    Are you somewhat confused between Serialization and Marshaling? This writing would break this confusion up, it would give you a basic understanding of the process of Serialization and the process of Marshaling, and how you can get the most out of each.
    Published Date : 10/May/2010
    First, this writing concentrates of and compares between three programming languages, C#, C++/CLI, and ISO/ANSI C++. It discusses 9 rules that every developer should keep in mind while working with constructors, destructors, and finalizers and class hierarchies:
    Published Date : 05/May/2010
    This article explains how to filter rows in a DataSet/DataTable. The example provided will help you get information faster.
    Published Date : 23/May/2010
    In this article, I will explain three basic terms of C#, such as Call Stack ,Call Site and stack Unwinding
    Published Date : 17/Aug/2010
Comments
By:JvDate Of Posted:7/23/2010 1:29:09 AM
Unit testing new and override implementation
Hi, Please do check out my blog post on the same topic but using unit testing: http://ravichandranjv.blogspot.com/ It is titled - Unit & Mock Testing "New" and "Override" implementations Thanks, Reavichandran Jv
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top
</