sfedorov1982
sfedorov1982

Reputation: 651

Why can't you declare a static struct in C#, but they can have static methods?

// OK
struct MyStruct
{
    static void Foo() { }
}

// Error
static struct MyStruct
{
}

Upvotes: 47

Views: 43936

Answers (3)

yellowstar
yellowstar

Reputation: 231

The key point here is that the static modifier on a class enforces (among other things) that an instance of the class cannot be created. This is done by forcing a private constructor.

The CLR doesn't have any way to prevent an instance of a struct type from being created. Even if there is no public default constructor, simply declaring

struct S { }

S[] items = new S[]{1};

would create an instance of the struct with all of the associated memory set to zero bits.

Note that this is different from a reference type (class), where the same code would create a reference of the specified type (referencing no object aka null) but not an instance of the object itself.

Upvotes: 10

Tomas Petricek
Tomas Petricek

Reputation: 243106

Since you cannot create an instance of a static type, the behavior of static struct would be exactly the same as the behavior of static class. So, there is no reason for creating them. I think it would be theoretically possible to have a static struct but it would be confusing - how would you choose between static class and static struct if the behavior of the two was exactly the same?

Note that static methods inside a struct are quite useful as you can use them for operations related to the struct, for example DateTime.TryParse etc.

Technically speaking I don't think that the current C# compiler & runtime could produce something like a static struct, because internally (at the IL level) static class is a class that is marked as abstract and sealed. And I suppose that you cannot create a struct that would be abstract and sealed (in the IL).

Upvotes: 45

tvanfosson
tvanfosson

Reputation: 532595

I think the key, really, is that a struct is a value type, not a reference type. That would be like saying "There's only one instance of int for my entire program. It can have different values, but only one at a time." Further, whenever you pass a struct as an argument, it gets passed by value, that is, a copy of the struct is made and placed on the stack. This defeats the purpose of a static definition -- which should mean that there is only (ever) one instance of the thing being defined. If what you are trying to create is really a Singleton, a class is a much better way to handle that given that it has much better creation semantics than a struct.

Upvotes: 16

Related Questions