DCSIMG
Interesting Behavior with the New Modifier and Interfaces - Doron's .NET Space

Interesting Behavior with the New Modifier and Interfaces

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.

Published Saturday, February 09, 2008 4:18 PM by dorony
תגים:

Comments

# Overcoming IE Bug with a Custom SessionIDManager

Internet Explorer 6 has the most annoying bug in the world . When you click a window.open link in a modal

Friday, February 15, 2008 9:04 PM by Doron's .NET Space

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: