Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// Infinite loop
var x = new { Items = new List<int> { 1, 2, 3 }.GetEnumerator() };
while (x.Items.MoveNext())
{
Console.WriteLine(x.Items.Current);
}
// Mutable struct used in all the following samples
struct Mutable
{
public Mutable(int x, int y)
: this()
{
X = x;
Y = y;
}
public void IncrementX() { X++; }
public int X { get; private set; }
public int Y { get; set; }
}
//------------- Arrays versus other collections -------------//
List<Mutable> lm = new List<Mutable> { new Mutable(x: 5, y: 5) };
lm[0].IncrementX(); // Mutating a copy, lm[0].X is 5
lm[0].X++; // Fails to compile. lm[0] is not a lvalue.
Mutable[] am = new Mutable[] { new Mutable(x: 5, y: 5) };
am[0].IncrementX(); // Mutating the element. lm[0].X is 6
am[0].X++; // Ok
// The same can be achieved if a property returns an element by ref in C# 7
//------------- Readonly modifier and a hidden copy -------------//
class B
{
public readonly Mutable M = new Mutable(x: 5, y: 5);
}
var b = new B();
b.M.IncrementX(); // mutates a copy
// Every access to a readonly field creates a temporary copy
// that is used in the following operation
//------------- using statement and a hidden copy -------------//
struct Disposable : IDisposable
{
public bool Disposed { get; private set; }
public void Dispose() { Disposed = true; }
}
var d = new Disposable();
using (d)
{
Console.WriteLine(d);
}
Console.WriteLine(d.Disposed); // false
// 'using' block creates a temporary copy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment