inheritance - C# prevent base class method from being hidden by new modifier in the derived class -
here's situation. in java can mark method final in base/super class , there no way derived class can mask method of same signature. in c# however, new keyword allows inheriting class create method same signature.
see example below. need keep orignal.myclass public please don't suggest answer. seems lost feature moving java c#
public class orignal.myclass{ public void mymethod() { // } } class fake.myclass: orignal.myclass { // how prevent following public new void mymethod() { // different } }
edit: not duplicate.
all answers seem suggest, it's not possible prevent method being hidden/shadowed in derived class. became apparent while migrating old java code c#. final method in java not let use same method signature in derived class. while it's great in scenarios c# allows method of same signature in derived class, have been great prevent such behavior if warranted.
// how prevent following
there no way prevent this. it's allowed language.
note that, in practice, matters. if expect base class used as class, method still called. using new
hides method when using derivedclass
a variable declared derivedclass
.
this means api, if built around myclass
, still call mymethod
when instances passed methods.
edit in response comments:
if worried people subclassing class in general, real option have seal class:
public sealed class myclass {
this prevent people creating subclass entirely. if want allow people derive class, however, there no way prevent them hiding method in class.
Comments
Post a Comment