Interesting Behavior with the New Modifier and Interfaces

February 9, 2008

tags:
no comments

Consider the following code. What will be the result of calling Test.TestInterface()?

    public interface IInterface

    {

        void DoSomething();

    }

 

    public class Father : IInterface

    {

 

        public void DoSomething()

        {

            Console.WriteLine(“Father Called”);

        }

 

    }

 

    public class Son: Father

    {

        public new void DoSomething()

        {

            Console.WriteLine(“Son Called”);

        }

    }

 

    public class Test

    {

        public void TestInterface()

        {

            IInterface tester = new Son();

            tester.DoSomething();

        }

    }

Note that Father is implementing the interface, but the son is hiding the interface method with the new modifier. Logic dictates (well, at least my logic did), that when you access the son through the interface, the son’s method will be called and not the father’s. After all, why should it matter who in my hierarchy implemented the Interface?

Well, apparently it does matter, and this will print “Father Called”. If we change Son to implement the interface by itself, i.e.

    public class Son: Father, IInterface

    {

        public new void DoSomething()

        {

            Console.WriteLine(“Son Called”);

        }

    }

Running the test will now print “Son Called”. Seems like the method of the last object in the hierarchy that explicitly states that it is implementing the Interface, gets called. Since “DoSomething” was not virtual, and the son hides it and not overrides it, the method that gets called in the first example is the Father’s. And yes, I discovered this the hard way.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*