When should you use struct and not class in C#? My conceptual model is that structs are used in times when the item is merely a collection of value types. A way to
A struct is a value type. If you assign a struct to a new variable, the new variable will contain a copy of the original.
public struct IntStruct {
public int Value {get; set;}
}
Excecution of the following results in 5 instances of the struct stored in memory:
var struct1 = new IntStruct() { Value = 0 }; // original
var struct2 = struct1; // A copy is made
var struct3 = struct2; // A copy is made
var struct4 = struct3; // A copy is made
var struct5 = struct4; // A copy is made
// NOTE: A "copy" will occur when you pass a struct into a method parameter.
// To avoid the "copy", use the ref keyword.
// Although structs are designed to use less system resources
// than classes. If used incorrectly, they could use significantly more.
A class is a reference type. When you assign a class to a new variable, the variable contains a reference to the original class object.
public class IntClass {
public int Value {get; set;}
}
Excecution of the following results in only one instance of the class object in memory.
var class1 = new IntClass() { Value = 0 };
var class2 = class1; // A reference is made to class1
var class3 = class2; // A reference is made to class1
var class4 = class3; // A reference is made to class1
var class5 = class4; // A reference is made to class1
Structs may increase the likelihood of a code mistake. If a value object is treated like a mutable reference object, a developer may be surprised when changes made are unexpectedly lost.
var struct1 = new IntStruct() { Value = 0 };
var struct2 = struct1;
struct2.Value = 1;
// At this point, a developer may be surprised when
// struct1.Value is 0 and not 1