Is there way for a class to 'remove' methods that it has inherited?
E.g. if I don't want my class to have a ToString()
method can I do something so that it is no longer available?
Is there way for a class to 'remove' methods that it has inherited?
E.g. if I don't want my class to have a ToString()
method can I do something so that it is no longer available?
No - this would violate Liskov's Substitution Principle. You should always be able to use an instance of a subtype as if it were an instance of a supertype.
Don't forget that a caller may only be aware of your type "as" the base type or an interface. Consider this code:
That would have to compile, wouldn't it? Now what would you expect to happen at execution time?
Now for
ToString
,GetHashCode
,Equals
andGetType
there's no way to avoid having them in the first place - but usually if there are methods you want to "remove" from a base type, that suggests you shouldn't be inheriting from it in the first place. Personally I find the role of inheritance is somewhat overplayed in object oriented programming: where it's useful it's really useful, but generally I prefer composition over inheritance, and interfaces as a form of abstraction rather than base classes.Short awnser, NO as all classes inherit from object and object has this method.
As others pointed out, you can't "remove" a method, but if you feel it has wronged you in some way you can hide it in your derived class.
From Microsoft's documentation (now retired):
You can throw a NotSupportedException, mark it as Obsolete and use EditorBrowsable:
EDIT:
As pointed out by others: I describe a way to "disable" methods, but you have to think about carefully, where you want to use this. Especially throwing exceptions can be a very dangerous thing.