A struct or a class binds a set of data and the related behavior in a logical unit. This logical unit is like a blueprint for a more abstract data type in our program than those built into the language. So does that mean structs and classes are interchangeable? When would you use a struct instead of a class or vice versa? This article highlights the differences between structures and classes and discusses the use cases of each with examples.


adriancole:

The general rule to follow is that structs should be small, simple (one-level) collections of related properties, that are immutable once created; for anything else, use a class.

C# is nice in that structs and classes have no explicit differences in declaration other than the defining keyword; so, if you feel you need to "upgrade" a struct to a class, or conversely "downgrade" a class to a struct, it's mostly a simple matter of changing the keyword (there are a few other gotchas; structs can't derive from any other class or struct type, and they can't explicitly define a default parameterless constructor).


posted by Elphy: 1047 days ago