Skip to content

Instantly share code, notes, and snippets.

@jacebennett
Created January 28, 2014 23:35
Show Gist options
  • Save jacebennett/8678860 to your computer and use it in GitHub Desktop.
Save jacebennett/8678860 to your computer and use it in GitHub Desktop.
Implicit Conversions are just syntax sugar
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'.
}
}
@jacebennett
Copy link
Author

@adamrmoss told me about this the morning. I didn't want to believe him. But, as usual, he was right.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment