Chris <ch************@cns-service.com> wrote:
In C# 2.0, the "static" keyword can be applied to a class. Doing so
already makes it "sealed". The compiler complains if you add both.
Although everthing in the class is static, you still have to apply the
"static" keyword to all fields, properties, methods, etc.
In all versions of C# (and .NET), you can also declare a type
initializer. While a private constructor is one way of implementing
the a singleton class, it can often be achieved using the type
initializer.
They're both part of the normal singleton pattern. The point of
providing a private constructor is to prevent instantiation from other
classes.
By default, if a no constructor is provided a parameterless constructor
is provided for you. If a type initializer is specified, there is no
need to declare a private constructor because the "new" keyword will be
disallowed.
That's not true. Here's a short but complete program demonstrating
this:
using System;
class SupposedSingleton
{
static SupposedSingleton()
{
Console.WriteLine ("Static constructor");
}
}
class Test
{
static void Main()
{
// For a real singleton, this shouldn't be allowed
SupposedSingleton s = new SupposedSingleton();
}
}
If you want both an instance and "static" constructor, you
must explicitly declare them both.
Nope - the compiler takes no notice of static constructors when
considering whether or not to provide a default constructor.
From the C# 1.1 spec:
<quote>
If a class contains no instance constructor declarations, a default
instance constructor is automatically provided.
</quote>
Note the "instance" part.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog:
http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too