Skip to content

Instantly share code, notes, and snippets.

@svick
Created February 12, 2015 14:13
Show Gist options
  • Save svick/da8139bac0f573edcc64 to your computer and use it in GitHub Desktop.
Save svick/da8139bac0f573edcc64 to your computer and use it in GitHub Desktop.
using System;
static class Program
{
private static void Main()
{
Intermediary<C>();
Console.WriteLine();
Intermediary<S>();
}
private static void Intermediary<T>() where T : I<T>, new()
{
T x = new T();
ByValueExtension(x);
x.Dump();
ByReferenceExtension1(ref x);
x.Dump();
ByReferenceExtension2(ref x);
x.Dump();
}
private static void ByValueExtension<T>(this T x) where T : I<T>
{
x.M1();
}
// you want to allow this for value types
private static void ByReferenceExtension1<T>(ref T x) where T : I<T>
{
x.M1();
}
// but forbid this for reference types
private static void ByReferenceExtension2<T>(ref T x) where T : I<T>
{
x = x.M2();
}
private static void Dump(this object o)
{
Console.WriteLine(o);
}
}
interface I<T> where T : I<T>
{
void M1();
T M2();
}
class C : I<C>
{
public int Field;
public void M1()
{
Field++;
}
public C M2()
{
return new C { Field = 10 * Field };
}
public override string ToString()
{
return Field.ToString();
}
}
struct S : I<S>
{
public int Field;
public void M1()
{
Field++;
}
public S M2()
{
return new S { Field = 10 * Field };
}
public override string ToString()
{
return Field.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment