When we have new
in C#, that personally I see only as a workaround to override a property that does not have a virtual/overridable declaration, in VB.NET we have two "concepts" Shadows
and Overloads
.
In which case prefer one to another?
When we have new
in C#, that personally I see only as a workaround to override a property that does not have a virtual/overridable declaration, in VB.NET we have two "concepts" Shadows
and Overloads
.
In which case prefer one to another?
Shadows
is for cases where your base class isFunction SomeMethod() As String
and you want to haveFunction SomeMethod() As Integer
. Basically, to change the return type.Overloads
is for case where your base class isFunction SomeMethod() As String
and you want to add a parameter such asFunction SomeMethod(ByVal value As Integer) As String
.There are three closely related concepts; overriding, shadowing and overloading.
Overriding is when you make a new implementation for a virtual method.
Shadowing is when you make a new non-virtual implementation for a method.
Overloading is when you add a method with the same name but different parameters.
All three concepts are available both in C# and VB.
I have actually confirmed by compiling the same code with
Shadows
vsOverloads
for a method with an identical name and signature in the base class and looking at the output fromildasm
for both. The only difference is theOverloads
case specifieshidebysig
.The significance of this is best explained by Jon Skeet in this answer.
But simply it means there is only a real difference if the base class has overloads of the method being redefined:
Shadows
will cause all of those overloads to be uncallable through the derived class, where asOverloads
only replaces the one method.Note that this is only a language construct and not enforced by the CLI (i.e. C# and VB.NET enforce this but other languages may not).
A simple code example:
The output of the above:
The output shows the
Shadows
calls are used whenC2
is called directly and not when called indirectly throughC1
.