Tigraine

Daniel Hoelbling-Inzko talks about programming

override vs new in C#

Posted by Daniel Hölbling on February 25, 2009

The class diagram is rather simple:

image

Yes, it’s that simple. I have an Image and I want to modify the behavior of the Url getter method for it (I can’t compose the URL string inside a Linq to Sql expression since I’d have to call a resolveFileType method that can’t get translated into SQL). So, I figured the best way to solve that problem is to have a subclass with a custom implementation of Url to handle that. I supply the required information through the ctor and when called the Url gets composed. The general idea is to assign an BoxImage to an Image field, hiding the custom implementation from the rest of the code.

Since I had not marked my fields as virtual I could not override them, I thought just writing new would do the job.
That failed miserably.

Actually, the new keyword does not hide the base classes method. Instead, a new method gets created that lives only on the derived class and that won’t get called if you are calling the base type.

public class Image
{
    public bool Url()
    {
        return true;
    }
}

public class BoxImage : Image {     public new bool Url()     {         return false;     } }

public class Image_Fixture {     [Fact]     public void Should_Return_False()     {         Image img = new BoxImage();         Assert.True(img.Url());         Assert.False(((BoxImage)img).Url());     } }

The unit test should be self explanatory, only if the type that gets the call is actually a BoxImage the new method will get called, if not, the base implementation will get used and your polymorphism goes out of the window :).

Doing this right would require the Url method to be virtual so you can properly override it:

public class Image
{
    public virtual bool Url()
    {
        return true;
    }
}

public class BoxImage : Image {     public override bool Url()     {         return false;     } }

public class Image_Fixture {     [Fact]     public void Should_Return_False()     {         Image img = new BoxImage();         Assert.False(img.Url());         Assert.False(((BoxImage)img).Url());     } }

Oh, and by the way. If you got the impression I don’t know about the fundamentals of the language I’m using, you are right. I try to learn as I encounter the problems, one feature at a time, one minor annoyance at a time :).

Filed under net, programmierung
comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more