Create a gist now

Instantly share code, notes, and snippets.

Generic constraint on boxing
using System;
interface IAdd
{
void Add(int val);
}
struct Foo : IAdd
{
public int value;
void IAdd.Add(int val)
{
value += val;
}
public void AddValue(int val)
{
value += val;
}
public void Print(string msg)
{
Console.WriteLine(msg + ":" + value);
}
}
class Program
{
static void Add_WithoutConstraints<T>(ref T foo, int val)
{
((IAdd)foo).Add(val);
}
static void Add_WithConstraints<T>(ref T foo, int val) where T : IAdd
{
foo.Add(val);
}
static void Main(string[] args)
{
Foo f = new Foo();
f.value = 10;
f.Print("Initial Value");
f.AddValue(10);
f.Print("After calling AddValue");
((IAdd) f).Add(10);
f.Print("After calling IAdd.Add");
Add_WithoutConstraints<Foo>(ref f, 10);
f.Print("After Add_WithoutConstrats");
Add_WithConstraints<Foo>(ref f, 10);
f.Print("After Add_WithConstraints");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment