Can't create a static class!

  • Thread starter Thread starter pigeonrandle
  • Start date Start date
P

pigeonrandle

Hi,
Can anyone tell me why i cant create the following class as 'static':

//Start

using System;

namespace WinAppSQL.windows
{
public static class WinAPI
{
public static int go() { return 1; }
}
}

//End

The compiler refuses! I'm using VS2003 framework 1.1.4322 SP1.

Cheers,
James.
 
pigeonrandle said:
Hi,
Can anyone tell me why i cant create the following class as 'static':

//Start

using System;

namespace WinAppSQL.windows
{
public static class WinAPI
{
public static int go() { return 1; }
}
}

//End

The compiler refuses! I'm using VS2003 framework 1.1.4322 SP1.

Because classes can't be marked static?

If you want a class to be non-creatable, give it a private default
constructor:

class ICantBeInstantiated
{
private ICantBeInstantiated()
{ }
}

It's up to you as the class implementer to not create any instances
within the class itself...
 
pigeonrandle,

Static class was introduced in .NET 2.0. You can simulate this behavior in
..NET 1.x, but not completely.
 
All,
Thankyou for you words of wisdom. I will use a private constructor.

Cheers,
James.
 
Stoitcho said:
pigeonrandle,

Static class was introduced in .NET 2.0. You can simulate this behavior in
.NET 1.x, but not completely.

What else is there to a static class beyond (a) non-instantiability,
and (b) some static methods?

(not being sarcastic - I just don't know)

Thanks,

cdj
 
I knew that someone will ask this :)

You cannot declare instance members (inlcuding constructor) for a class
declared as *static* this restriction cannot be enforced in .NET 1.x. This
doesn't affect functionality, but it may help discovering errors at compile
time. That is what I had in mind.
 
Stoitcho said:
I knew that someone will ask this :)

You cannot declare instance members (inlcuding constructor) for a class
declared as *static* this restriction cannot be enforced in .NET 1.x. This
doesn't affect functionality, but it may help discovering errors at compile
time. That is what I had in mind.

There's slightly more, actually.

In C# 1.1 there's no way of creating a type without an instance
constructor *at all* - if you don't specify one yourself, a default one
will be provided.

A static class not only doesn't allow you to declare an instance
constructor, but the class will not have one, so you can't instantiate
it even with reflection.

Jon
 
Methods and constructors can be static, not the class itself in 1.1.
You do not need to instantiate the static class to access static
members.

namespace WinAppSQL.windows
{
public class WinAPI
{
static WinAPI()
{
// static constructor login here
}

public static int go() { return 1; }
}
}
 
Back
Top