// OK struct MyStruct { static void Foo() { } } // Error static struct MyStruct { }
Yes, thanks. The original wording could have been misinterpreted by beginning C programmers to develop a misconception along "Oh, static variables must be used with caution, so they must be bad in some way.
A structure declaration cannot be declared static, but its instancies can. You cannot have static members inside a structure because the members of a structure inherist the storage class of the containing struct. So if a structure is declared to be static all members are static even included substructures.
static member inside struct will limit its scope but usually static member must be shared(based on its scope) and hence we cannot use it in struct.
A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With