C# Inheritance with the New Modifier

Environment: C#

Introduction

If you come from C++ or Java background to C#, no wonder that you will notice some strange keywords introduced to this new language. The first reaction will be what are these things for and why were they added Specially that, till now people were able to develop programs using the existing languages without problems. Among the set of new keywords added to C# there are new and override modifiers. Although new may not seem that new to you , however its usage as method modifier is completely new.

The new Modifier

Similarly to C++ , C# allow redefinition of inherited methods in the derived classes at the cost of hiding the inherited ones. Although hiding is not an error, but it does cause the compiler to issue a warning. To suppress this warning you have to include the new modifier in the derived method.

The real benefit of this feature is to be sure that you intentionally want to hide the base method and this did not happen by accident or misspelling. Conversely, if you declare a method as new and it does not really hide a base method, the compiler will also issue a warning, that can be suppressed by removing the new modifier.

Consider the following example :

public class baseHello
{
 public void sayHello()
 {
  System.Console.WriteLine("base says hello");
 }
}
 
class derivedHello:BaseHello
{
 public void sayHello()
 {
  System.Console.WriteLine("derived says hello");
 }
}

The preceding code will compile fine but the compiler warns you that method derivedHello.sayHello() hides the method baseHello.sayHello() :

warning CS0114: 'derivedHello.sayHello()' hides inherited member 'baseHello.sayHello()'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.

As the warning suggest it is preferable to use new like the following.

class derivedHello:BaseHello
{
 new public void sayHello()
 {
  System.Console.WriteLine("derived says hello");
 }
}

The override Modifier

As you certainly know, every object oriented language implements polymorphism which is summarized by having multiple implementation for the same interface.

While all methods in Java are virtual by default, C++ and C# require clearly defining a method as virtual , by using virtual modifier in C++ and C# or abstract modifier in C# only (abstract is equivalent to pure virtual in C++ : virtual type methodName(some params) = 0; )

In order to give a different version for the same method it suffice to derive the base class and redefine the virtual method using same name and signature, but with different body, plus the override modifier. This may seem annoying at the beginning specially that C++ and Java developers did not have to do that. However experience with large projects has shown that lots of runtime problems occur when some modifications were needed in the virtual base method signature ,which necessarily require the same modification in all the derived classes that give their own version.

Look at this Java example :

public class baseHello
{
 public void sayHello()
 {
  System.out.println("baseHello says HELLO");
 }
}
  
public class derivedHello extends baseHello
{
 public void sayHello()
 {
  System.out.println("derivedHello says HELLO");
 }
}

In the above example the class derivedHello inherits and redefines the method sayHello() from baseHello class.

Now suppose that at some time in the project the designer find out that the sayHello() method should take a String parameter .

The change in the baseHello will be as follows

Public class baseHello
{
 public void sayHello(String name )
 {
  System.out.println("baseHello says HELLO to "+name);
 }
}

Now the base class is modified and still the hard work to do is to modify all the derived classes that could be in dozens . Failing to modify one derived class will result in a behavior different than expected as the following code will show:

public class TestHello{
 public static void print(baseHello hello)
 {
  hello.sayHello("TestHello");
 }
  
 public static void main(String[] args)
 {
  baseHello baseH= new baseHello();
  derivedHello derivedH= new derivedHello();
  print(baseH);
  print(derivedH);
 }
}

Running the TestHello class will result in two identical strings

baseHello says HELLO to TestHello

baseHello says HELLO to TestHello

The reason is because you failed to change the derivedHello class to be conform to the baseHello class so the latter is used when hello.sayHell("TestHello") is called.

Because the java compiler does not have any idea that the sayHello() in derived class is intended to override the sayHello(String name) in the base class , it does not complain about it and considers it as a new method defined only in the derived class.

After exposing the problem, here is what C# offers to solve the problem.

Every method that must override a virtual base method must be declared with override modifier. The same example applied to C# becomes

public class BaseHello
{
 virtual public void sayHello(string name)
 {
  System.Console.WriteLine("BaseHello says hello to {0}",name);
 }
}
  
class DerivedHello:BaseHello
{
 // different signature
 override public void sayHello()
 {
  System.Console.WriteLine("DerivedHello says hello");
 }
}

The compilation of the example will result the following error :

error CS0115:DerivedHello.sayHello()': no suitable method found to override

Telling the method sayHello() in DerivedHello which is intended to override sayHello(String name) in BaseHello has different signature than its base method.

In such way no matter how many times a class is derived it is always possible to detect difference in methods name and signature at compile time.

Conclusion

As a conclusion , you have noticed that new and override modifiers have a key role in preventing runtime flaws and sparing hours of debugging.



Comments

  • Polymorphism

    Posted by Prathap on 11/02/2012 01:17am

    Java & C# is not same in polymorphism concept http://wisentechnologies.com/it-courses/.net-training.aspx

    Reply
  • Very Interesting C#

    Posted by Legacy on 05/23/2002 12:00am

    Originally posted by: Akhilesh A. Waoo

    I found your matter is very interesting as well as covers almost all the topics of C# language

    Reply
  • not really good.., a lot of things still cannot understand after reading...

    Posted by Legacy on 04/18/2002 12:00am

    Originally posted by: neptune

    as title

    not really good.., a lot of things still cannot understand after reading...

    Reply
  • only to look like new!!

    Posted by Legacy on 01/24/2002 12:00am

    Originally posted by: nesty

    a lot of surprise! creating sorts of flavor is good. how about J#, we will be waiting for it...but it look like it is just only to look like new and original...in the other hand it is getting more powerful and complicated...

    Reply
  • What if Base class method was not designed with Virtual modifier...

    Posted by Legacy on 11/13/2001 12:00am

    Originally posted by: Dev Sharp

    You are right that to override base class method ,you can delcare derive class method with Override Modifier,But what if the base class method was not declared with Virtual modifier when it was designed???In that case you cannot use Override Modifier...is there any solution for this ..

    Dev

    Reply
  • compile time error?

    Posted by Legacy on 09/18/2001 12:00am

    Originally posted by: matthijs

    This article talks about the advantage of the 'override' modifier. The compiler will complain about DerivedHello if you change the BaseHello class and recompile all. But does it also complain when you just recompile the BaseHello class? I don't think the compiler can know about every derived class of BaseHello. So you can still end up with run-time errors that are hard to track.
    How the jvm deals with compile- and run-time objects is very well defined in the language specification. I haven't (yet) looked at C# enough to know how it works, but I am very curious about it.

    Regards,
    Matthijs.

    Reply
  • All's well that ends well.

    Posted by Legacy on 07/11/2001 12:00am

    Originally posted by: TechnoWIZ

    All's well that ends well.
    yeh i mean what i say.
    as somebody commented "lets wait & watch ". i'm having the same thoughts. 'cause c# is new and i don't even have complete info about it but it seems to me as if its just a step ahead of java and others && nothing much is new about it.

    so lets wait & see where it ends.........

    Reply
  • So difficult !!

    Posted by Legacy on 06/29/2001 12:00am

    Originally posted by: Nonox

    MS'company had risk challenge...

    Reply
  • Wait 'n' Watch

    Posted by Legacy on 06/28/2001 12:00am

    Originally posted by: anukir

    Can't say anything , we have to wait & watch.

    anukir

    Reply
  • Feel the difference

    Posted by Legacy on 06/12/2001 12:00am

    Originally posted by: Swarup

    C# is not a JAVA clone. It's different!!!
    

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

  • For the third consecutive year, Neustar surveyed hundreds of companies on distributed denial of service (DDoS) attacks. Neustar's survey reveals evidence that the DDoS attack landscape is changing. The number of companies attacked is up, but attack duration is down. Larger attacks are more common, but most attacks are still less than 1 Gbps. More than half of attacked companies reported theft of funds, data or intellectual property. Read the full report to learn how DDoS attacks have evolved in both strategy …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds