Skip to content

Instantly share code, notes, and snippets.

@Warpten
Created November 14, 2018 08:41
Show Gist options
  • Save Warpten/73feeee3f1686217ab49d80f5e389a67 to your computer and use it in GitHub Desktop.
Save Warpten/73feeee3f1686217ab49d80f5e389a67 to your computer and use it in GitHub Desktop.
using System;
public interface Base {
int Property { get; }
void Mutate(int someValue);
}
public struct SuperA : Base {
public int Property { get; private set; }
public void Mutate(int someValue) {
Property = someValue;
}
}
public struct SuperB : Base {
public int Property {get;}
public void Mutate(int someValue) { /* no-op */ }
}
public abstract class ObjBase {
public abstract ref readonly Base Value { get; }
}
public class Obj : ObjBase {
private Base _property = new SuperA();
public override ref readonly Base Value => ref _property;
}
public class Program {
public static void Main(String[] args) {
ObjBase o = new Obj();
o.Value.Mutate(42);
Console.WriteLine(o.Value.Property); // 42
// This compile when making ObjBase.Value ref-return
// instead of ref-reaonly-return.
// o.Value = new SuperB();
o.Value.Mutate(666);
Console.WriteLine(o.Value.Property); // 0 if not readonly, 666 otherwise
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment