Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to prevent a class from being Instantiated?

Tags:

c#

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?

like image 991
Romesh Somani Avatar asked Apr 13 '12 12:04

Romesh Somani


1 Answers

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.

like image 130
Jon Skeet Avatar answered Oct 10 '22 15:10

Jon Skeet