Wednesday, April 27, 2011

How to prevent class from being instantiated.

1) Make the class an abstract base class.

abstract class Person {
}
class Programmer : Person {
}
var person = new Person(); // compile time error
var programmer = new Programmer(); // ok
2) Create private constructor to class
class test
{
    // Private Constructor:
    private test{ }
    public static double e = System.Math.E;  //2.71828...
}

3) Static class

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

The main features of a static class are:

· They only contain static members.

· They cannot be instantiated.

· They are sealed.

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state

No comments:

Post a Comment