On Jul 28, 7:33*pm, Author <gnewsgr...@gmail.comwrote:
In general, in OO design, how do we determine if we should use struct
or class?
A few distinguishing traits:
1) It is data-centric, not behavior-centric - e.g. Point is just a
tuple of two ints, Person is an entity with encapsulated operations.
Most methods on structs are just helpers to manipulate data, and could
usually be refactored as external methods. Most methods on classes
should encapsulate business logic related to entities those classes
model.
2) It has no identity - two structs are equal if the data within is
the same; for two structs with the same data, there is no way to
distinguish them, and using one in place of the other should give
identical results for any operation. C# enforces this by requiring
structs to define at least one field (since two identityless objects
which don't have data cannot be distinguished at all, so the result is
effectively a singleton). For example, if you get a Point with X=2 and
Y=3 from the first method, it is guaranteed that whether you pass that
same Point on to the second method, or create your own new Point with
the same values of X and Y and then pass that to the second method,
the actions performed by the second method will be exactly the same.
On the other hand, if you have two different Person instances, they
typically refer to two different people, even if their names (and
other data) match, so passing one instead of another to a business
method will do a different thing. In C#, this manifests itself in the
fact that classes have operator== which compares references (i.e. does
an identity comparison), and default implementation of Equals() for
classes also does reference comparison, while for structs Equals()
compares values of all fields, and there is no way to do a reference
comparison.
3) It is atomic with respect to updates - you cannot take an existing
Point and change just the X coordinate - the result would always be a
new Point. In C# terms, this means that structs are immutable (this
isn't enforced by the compiler, but is strongly recommended to follow
the practice nonetheless).
Simply put, the design difference between a struct and a class is the
difference between raw data (tuple, record, etc) and an entity. The
line can be blurry sometimes, but usually it is fairly obvious for
every specific case.
Of course, in real world, decision on using class vs struct is often
made for performance reasons - a good example is List<T>.Enumerator,
which is a struct, though it doesn't really fit the definition above.