The "struct" or "record" concept was created before the "class" concept. And sometimes, can be interchanged.
When to use a variable, field or instance of an struct:
(1) When Only Data members are need it, without methods. Or has few methods, that are barely used, such as constructors.
Example:
struct CoordinateStruct
{
int X;
int Y;
}
(2) When a great quantity of elements, are required, and since objects, use additional memory, sometimes not visible, migrating methods to a container element, such another object, a module (namespace) like object, or singleton object (Flyweight design pattern).
Before:
class PointClass
{
int X;
int Y;
// its also an object / class
Color Color;
public void assign(int NewX, int NewY, Color NewColor) { ... }
public void move(int addX, int addNewY) { ... }
}
// multiple element container
class CADAppClass
{
List<Point> Points;
// ...
}
// Not enough memory Exception !!!
After:
struct PointStruct
{
int X;
int Y;
// its a low memory integer
int Color;
}
// multiple element container
class CADAppClass
{
List<Point> Points;
public void assignPoint
(ref PointStruct Point, int NewX, int NewY, Color NewColor) { ... }
public void movePoint
(ref PointStruct Point, int addX, int addNewY) { ... }
// ...
}
(3) When you need to encapsulate the data elements, even if its a small quantity of elements, in a variable, even if there are methods, operators, events or "messages". The encapsulation, maybe for serializacion as an example (loading from D.L.L., DCOM, JSON, plain data files).
Before:
class CustomerClass
{
String FirstName;
String LastName;
public void Store(Stream Destination) { ... }
public void Load(Stream Source) { ... }
public void CopyTo(CustomerClass Destination) { ... }
public void CopyFrom(CustomerClass Source) { ... }
}
After:
struct CustomerStruct
{
char[100] FirstName;
char[100] LastName;
}
// one to one, nested, relationship, seems redudant,
// but required
Class CustomerClass
{
CustomerStruct Data;
public void Store(Stream Destination) { ... }
public void Load(Stream Source) { ... }
public void CopyTo(CustomerStruct Destination) { ... }
public void CopyFrom(CustomerStruct Source) { ... }
}
I used this one, with enumerations, instead of structs, in programming languages that are Object & Class Oriented, but, that doesn't treat enumerations as objects (Example: Object Oriented PHP & Object Pascal), as Java or C#, does.
(4) A mix of the previous cases, or a scenario, not considerated.
Cheers.