Information Technology Reference
In-Depth Information
Example of a Static Constructor
The following code uses a static constructor to initialize a private static field named RandomKey
of type Random . Random is a class provided by the BCL to produce random numbers. It is in the
System namespace.
class RandomNumberClass
{
private static Random RandomKey; // Private static field
static RandomNumberClass() // Static constructor
{
RandomKey = new Random(); // Initialize RandomKey
}
public int GetRandomNumber()
{
return RandomKey.Next();
}
}
class Program
{
static void Main()
{
RandomNumberClass a = new RandomNumberClass();
RandomNumberClass b = new RandomNumberClass();
Console.WriteLine("Next Random #: {0}", a.GetRandomNumber());
Console.WriteLine("Next Random #: {0}", b.GetRandomNumber());
}
}
One execution of the preceding code produced the following output:
Next Random #: 47857058
Next Random #: 1124842041
Accessibility of Constructors
Access modifiers can be assigned to constructors just as they can to other members. Notice
that in the examples, the constructors have been declared public so that you can create
instances from outside the class.
You can also create private constructors, which cannot be called from outside the class,
but can be used from within the class, as you shall see in the next chapter (which covers
inheritance).
Search WWH ::




Custom Search