struct PointStruct { public int X; public int Y; }
class PointClass { public int X; public int Y; }
var ps1 = new PointStruct { X = 5, Y = 10 };
var ps2 = ps1;
ps2.X = 20;
var pc1 = new PointClass { X = 5, Y = 10 };
var pc2 = pc1;
pc2.X = 20;
Console.WriteLine($"ps1.X = {ps1.X}, ps2.X = {ps2.X}");
Console.WriteLine($"pc1.X = {pc1.X}, pc2.X = {pc2.X}");Structs are copied by value, so changing ps2.X does not affect ps1.X.
Classes are copied by reference, so changing pc2.X also changes pc1.X.
struct MyStruct { public int Value; public void Increment() => Value++; }
class MyClass { public int Value; public void Increment() => Value++; }
var s = new MyStruct();
var c = new MyClass();
var sw = System.Diagnostics.Stopwatch.StartNew();
for (int i = 0; i < 10000000; i++) s.Increment();
sw.Stop();
var structTime = sw.ElapsedMilliseconds;
sw.Restart();
for (int i = 0; i < 10000000; i++) c.Increment();
sw.Stop();
var classTime = sw.ElapsedMilliseconds;
Console.WriteLine($"Struct time: {structTime} ms");
Console.WriteLine($"Class time: {classTime} ms");Struct method calls are generally faster because they avoid heap allocation and pointer dereferencing.
Class method calls involve reference indirection and possible heap overhead.
struct Data {
public int A;
public int B;
public void Update() {
A = 10;
B = 20;
}
}
Data d = new Data();
d.Update();
Console.WriteLine($"A = {d.A}, B = {d.B}");
Data d2 = d;
d2.A = 30;
Console.WriteLine($"d.A = {d.A}, d2.A = {d2.A}");Structs are copied on assignment, so d2 is a separate copy of d.
Changing d2.A does not affect d.A.
struct Point { public int X; public int Y; }Option A uses correct object initializer syntax.
Options B and C are invalid because Point has no constructor defined.
Option A uses invalid syntax.
Structs store data inline, reducing heap allocations and improving cache locality.
Classes have overhead due to heap allocation and references.
Inheritance is not needed here.
