Default TypeConverters and Objects

Take a look at the following code. Which of the following tests do you think should pass?

public static TypeConverter converter;

[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
   converter = TypeDescriptor.GetConverter(typeof(object));
}

[TestMethod]
public void ObjectFromString()
{
   Assert.IsTrue(converter.CanConvertFrom(typeof(string)));
}

[TestMethod]
public void ObjectFromInt()
{
   Assert.IsTrue(converter.CanConvertFrom(typeof(int)));
}

[TestMethod]
public void ObjectFromDouble()
{
   Assert.IsTrue(converter.CanConvertFrom(typeof(double)));
}

[TestMethod]
public void ObjectFromDateTime()
{
   Assert.IsTrue(converter.CanConvertFrom(typeof(DateTime)));
}

[TestMethod]
public void StringToObject()
{
   var stringConverter = TypeDescriptor.GetConverter(typeof(string));
   Assert.IsTrue(stringConverter.CanConvertTo(typeof(object)));
}

[TestMethod]
public void IntToObject()
{
   var intConverter = TypeDescriptor.GetConverter(typeof(int));
   Assert.IsTrue(intConverter.CanConvertTo(typeof(object)));
}

[TestMethod]
public void DoubleToObject()
{
   var doubleConverter = TypeDescriptor.GetConverter(typeof(double));
   Assert.IsTrue(doubleConverter.CanConvertTo(typeof(object)));
}

[TestMethod]
public void DataTimeToObject()
{
   var objectConverter = TypeDescriptor.GetConverter(typeof(DateTime));
   Assert.IsTrue(objectConverter.CanConvertTo(typeof(object)));
}

You might think that type converters could convert any type to an object, but you’d be wrong.  Value types or reference types, it doesn’t matter. All of these tests return false. Neither the object type converter nor any of the other type converters know how to do this conversion. I’ve asked Bill why this is the case, and I’ll have a new post on why this is true as soon as we know. Until then, I say that default TypeConverters aren’t very smart.

This entry was posted in C#. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>