2007-08-10

C#: Generic type conversion

I've come across a strange restriction of generic in C#. The only good thing is the most problems appear  during programming the popular language are solved by a second query to google.

Because of the error "Cannot convert type 'string' to 'T'" instead of the evident:

do so
public static T GetSetting<T>(string key)
{
   return (T)ConfigurationManager.AppSettings[key];
}

write like this:

public static T GetSetting<T>(string key) where T : IConvertible
{
   return (T)Convert.ChangeType(ConfigurationManager.AppSettings[key], typeof(T));
}





Update 13.08.2007: And in addition, in spite of autoboxing the problem with simple type arrays is remained. If we have variable of type Object which stores array of strings that one can easy get n value with explicit cast, everything has become more interesting with array of integers:

[Test]
public void testCastArray()
{
Object object_arr = new String[] { "a", "b", "c" };
Object[] object_arr_cust = (Object[])object_arr;
Assert.AreEqual(object_arr_cust[1], "b");

Object value_arr = new Int32[] { 1, 2, 3 };
Array value_arr_cust = (Array)value_arr;
Assert.AreEqual(value_arr_cust.GetValue(1), 2);
}

[Test]
[ExpectedException(typeof(InvalidCastException))]
public void testInvalidArrayCast()
{
Object value_arr = new Int32[] { 1, 2, 3 };
Object[] value_arr_cust = (Object[])value_arr;
Assert.AreEqual(value_arr_cust[1], 2);
}

No comments:

Post a Comment