Wednesday, February 3, 2010

Why shadowing properties and methods is NOT a good thing!

I know it's old news but it's never too much to add emphasis on this:

Thou SHALL NOT shadow properties or methods.

And heres why.

Consider the following classes:

Class Class1

    Property BaseProperty = " Base Property "
    Overridable Property OverridableProperty = " Overridable Property "

End Class

Class Class2
    Inherits Class1

    Shadows Property BaseProperty = " Shadow Property "
    Overrides Property OverridableProperty = " Overriden Property "

End Class


Pretty simple and basic.

Now, consider the following method:

Sub Main()

    Dim c1 = New Class1
    Dim c2 = New Class2

    Console.WriteLine("c1.BaseProperty = " & c1.BaseProperty)
    Console.WriteLine("c2.BaseProperty = " & c2.BaseProperty)
    Console.WriteLine("CType(c2, Class1).BaseProperty = " & CType(c2, Class1).BaseProperty)
    Console.WriteLine()

    Console.WriteLine("c1.OverridableProperty = " & c1.OverridableProperty)
    Console.WriteLine("c2.OverridableProperty = " & c2.OverridableProperty)
    Console.WriteLine("CType(c2, Class1).OverridableProperty = " & CType(c2, Class1).OverridableProperty)
    Console.WriteLine()

    Console.ReadLine()

End Sub


And its result:

c1.BaseProperty = Base Property
c2.BaseProperty = Shadow Property
CType(c2, Class1).BaseProperty = Base Property

c1.OverridableProperty = Overridable Property
c2.OverridableProperty = Overriden Property
CType(c2, Class1).OverridableProperty = Overriden Property

And that's why, young Grashopper, you should never shadow properties or methods.

You have no control over what's the user will do.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home