Skip to content

Instantly share code, notes, and snippets.

@yizhang82
Created March 19, 2017 07:25
Show Gist options
  • Save yizhang82/f449cfef5cc92ed089bd759cfd2debcd to your computer and use it in GitHub Desktop.
Save yizhang82/f449cfef5cc92ed089bd759cfd2debcd to your computer and use it in GitHub Desktop.
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