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. The type initializer can also be used to perform type
initialization logic, which could include initializing fields, etc.
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. If you want both an instance and "static" constructor, you
must explicitly declare them both.
Here's a simple example:
public class Foo
{
private static readonly _firstName;
private static readonly _lastName;
private static _fullName;
public static string FirstName
{
get
{
return _firstName;
}
}
public static string LastName
{
get
{
return _lastName;
}
}
public static string FullName
{
get
{
if ( _fullName == null )
{
if ( _firstName == null && _lastName == null )
_fullName = string.Empty;
else if ( string.IsNullOrEmpty( _firstName ) )
_fullName = _lastName;
else if ( string.IsNullOrEmpty( _lastName == null ) )
_fullName = _firstName;
else
_fullName = string.Format( "{0} {1}", _firstName,
_lastName );
}
return _fullName;
}
}
// notice that scope cannot be applied to a type initializer, nor
can it have any parameters
static Foo()
{
_firstName = "Real";
_lastName = "Foo";
}
}