C# prohibit upcast


C# prohibit upcast



Is there a way to prohibit implicit upcast of a paticular class ?



I want the compiler to throw an error if a function accepting MyBase is passed an instance of MyDerived (same for assignment etc)



My use case is trying immitate c++ typedef by inheriting but upcasting break this.





No, you cannot. A MyDerived is a MyBase, by definition.
– Damien_The_Unbeliever
Jul 3 at 6:37


MyDerived


MyBase





Pretty unclear how you got into this horrible pickle, do stop trying to imitate C++. The result is doomed to turn into C--. The C# language supports type aliases with the using statement.
– Hans Passant
Jul 3 at 11:05





using using is lame and only works in file scope
– kofifus
Jul 3 at 11:32




1 Answer
1



No. You can't do that on compile time. It is a derived class after all. It it its purpose to do so. You can on run time, but I don't think you want that.



You can make MyBase sealed if you don't want any derived type to exist.


MyBase



I do wonder why you would want this, but that is a whole different question...





the reason is in the question
– kofifus
Jul 3 at 11:33





If your reason is "My use case...", then explain that in more detail. It is absolute unclear why you'd want this.
– Patrick Hofman
Jul 3 at 11:34






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

JMeter fails on beanshell imports

Why in node-red my HTTP POST no receive payload from inject?

PHP contact form sending but not receiving emails