Saturday, September 13, 2008

C# : new vs. override

new:

  • just to be sure that you intentionally want to hide the base method
  • no base method - derived used new --> compiler warning Warning 1 'Types.Derived.Foo()' hides inherited member 'Types.Base.()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.
override:
  • derived has to explicitly override that base method.
  • base has Foo(int) and derived overrides, then if base changes the signature to Foo(long) then derived no longer overriders it, it has its own function. Error 2 'Types.Derived.FooNotInBase()': no suitable method found to override.

If you upcast, then "new" executes base and "override" executes derived.

Base b = new Derived();
Derived d = new Derived();
b.FooWithNew(); //Base FooWithNew
b.FooWithOverride(); //Derived FooWithOverride
d.FooWithNew(); //Derived FooWithNew
d.FooWithOverride(); //Derived FooWithOverride

In C#, functions are overloads are impemented as "hide by signature", so if base has Foo(int) and Foo(long) and Derived as Foo(int) then Foo(long) from base is not hidden.

No comments: