AdvancedLesson 15 of 16
Value Types, IDisposable & Span – C#
How memory, copies and resources work in .NET.
struct is a value type (copied on assignment), class a reference type (assignment only copies the reference). This decides whether a change becomes visible through a second variable.
var a = new WertPunkt(1, 2);
var b = a;
b.X = 99;
Console.WriteLine(a.X); // 1 (b is a copy)
var c = new RefPunkt { X = 1 };
var d = c;
d.X = 99;
Console.WriteLine(c.X); // 99 (c and d point to the same object)
struct WertPunkt
{
public int X;
public int Y;
public WertPunkt(int x, int y) { X = x; Y = y; }
}
class RefPunkt { public int X; }The garbage collector cleans up memory automatically – but not files, sockets or database connections. That is what IDisposable and using are for; using guarantees that Dispose() is called:
using (var r = new Ressource("A"))
{
Console.WriteLine("working");
} // A released
using var r2 = new Ressource("B");
Console.WriteLine("End"); // afterwards: B released
class Ressource : IDisposable
{
private readonly string _name;
public Ressource(string name) => _name = name;
public void Dispose() => Console.WriteLine($"{_name} released");
}Span<T> and ReadOnlySpan<T> are views over contiguous memory (array, string, stack) without copying – important for high-performance parsers and text processing.
ReadOnlySpan<char> text = "Hello World";
ReadOnlySpan<char> wort = text[..5]; // no copy, no allocation
Console.WriteLine(wort.ToString()); // Hello
Span<int> puffer = stackalloc int[4]; // memory on the stack
puffer[0] = 7;
Console.WriteLine(puffer.Length); // 4WarningSpan types are
ref structs: they must not live in fields of classes and must not be held across an await. Large structs (more than about 16 bytes) are expensive to copy – then a class or a readonly struct with in parameters is better.