Created
January 28, 2014 23:35
-
-
Save jacebennett/8678860 to your computer and use it in GitHub Desktop.
Implicit Conversions are just syntax sugar
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 Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace UnitTestProject1 | |
{ | |
public class Foo | |
{ | |
public int Value { get; set; } | |
public Foo(int value) { Value = value; } | |
} | |
public class Bar | |
{ | |
public string Description { get; set; } | |
public static implicit operator Bar(Foo f) | |
{ | |
return new Bar { Description = string.Format("Foo({0})", f.Value) }; | |
} | |
} | |
public class Container | |
{ | |
public Bar BarProperty { get; set; } | |
} | |
[TestClass] | |
public class UnitTest1 | |
{ | |
[TestMethod] | |
public void SetItTyped() | |
{ | |
var container = new Container(); | |
var foo = new Foo(3); | |
container.BarProperty = foo; | |
Assert.AreEqual("Foo(3)", container.BarProperty.Description); | |
} | |
//Passes | |
[TestMethod] | |
public void SetItViaReflection() | |
{ | |
var container = new Container(); | |
var foo = new Foo(3); | |
var containerType = container.GetType(); | |
var propInfo = containerType.GetProperty("BarProperty"); | |
propInfo.SetValue(container, foo); | |
Assert.AreEqual("Foo(3)", container.BarProperty.Description); | |
} | |
//Test method UnitTestProject1.UnitTest1.SetItViaReflection threw exception: | |
//System.ArgumentException: Object of type 'UnitTestProject1.Foo' cannot be converted to type 'UnitTestProject1.Bar'. | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@adamrmoss told me about this the morning. I didn't want to believe him. But, as usual, he was right.