Created
March 19, 2017 07:25
-
-
Save yizhang82/f449cfef5cc92ed089bd759cfd2debcd to your computer and use it in GitHub Desktop.
Generic constraint on boxing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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