I recently discovered that structs in C# can have methods.
Quite accidentally, I found myself to have been using the static method of an empty struct in my code, rather than the static method of a static class that I thought I was working with!
e.g.
public struct Foo
{
public static void Bar(Param param)
{
...
}
}
It's not really being used as a struct at this point, as it has no properties at all!
Is this very different from using a static method of a class (static or otherwise)? Are there any reasons to prefer one over the other? (My gut tells me that using the static struct method is, at minimum, less intuitive)
A static class can only contain static members. A static method ensures that, even if you were to create multiple classB objects, they would only utilize a single, shared SomeMethod function. Technically, there's no difference, except that ClassA's SomeMethod must be static.
Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls . Static methods don't have access to cls or self . They work like regular functions but belong to the class's namespace.
A struct can have its own static and instance methods (or functions) but are not created within the struct itself. These methods exist in a separate block using impl and they can be either static or instance methods.
The static method uses compile-time or early binding. The non-static method uses runtime or dynamic binding. The static method cannot be overridden because of early binding. The non-static method can be overridden because of runtime binding.
No, static members belong to the type and not to instances of the type. There is no difference (neither with respect to performance nor semantics) between declaring static class members and static struct members.
It is important to note that if a type's only function is to contain static members, you should use a static class instead. With structs, there is an implicit and unchangeable public, no-argument constructor. If the type will not have any instance methods, the ability to create instances should be removed. Declaring a class static
is the same as declaring it abstract sealed
, so developers will not be able to accidentally create instances that have no purpose.
The behavior is no different. C# bastardized structs by hugely increasing the intersection of struct and class features. Personally I would just use a class because it seems more correct to me (certainly more in line with the conventions in most languages).
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