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

- 8,126
- 3
- 29
- 36

- 611
- 1
- 5
- 7
-
Just the same for [delegates](http://stackoverflow.com/questions/6835766/why-can-a-net-delegate-not-be-declared-static) and [enums](http://stackoverflow.com/questions/4567868/troubles-declaring-static-enum-c-sharp) – nawfal Jan 02 '14 at 17:05
-
I answer this question in another question. I hope to help you. [This is the link](https://stackoverflow.com/a/59360219/6755993) – Dec 16 '19 at 18:05
3 Answers
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).

- 8,126
- 3
- 29
- 36

- 240,744
- 19
- 378
- 553
-
fixed arrays can only be contained in structs, it would be nice to have a static one of these – Markus Sep 04 '19 at 10:10
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.

- 524,688
- 99
- 697
- 795
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.

- 2,130
- 3
- 26
- 38

- 231
- 2
- 4