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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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,EqualsandGetTypethere’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.