I need to know how to prevent a class from being Instantiated in .net?
I know few methods like making the class Abstract and Static.
Is there any more way to achieve this?
Making the class static is the best approach, if you absolutely don't want any instances. This stops anyone from creating instances. The class will be both sealed and abstract, and won't have any constructors.
Additionally, the language will notice that it's a static class and stop you from using it in various places which imply instances, e.g. type arguments and variables. This indicates the intention more clearly than just having a private constructor - which could mean that there are instances, created within that class (e.g. for a singleton implementation).
Oh, and making the class static will stop you from introducing any pointless instance members in the class, too :)
See MSDN for more information about static classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With