Reputation: 9746
Below is some quick code to illustrate my question. Any way to avoid this apparently unnecessary boxing/unboxing?
public class TestClass<T>
{
public T TestMethod()
{
if (typeof(T) == typeof(bool))
{
return true; // doesn't work
return (T)(object)true; // works, but any way to avoid this?
}
return default(T);
}
}
Upvotes: 6
Views: 1626
Reputation: 426
Make it a static field.
public class TestClass<T>
{
static T TrueIfBoolean = typeof(T) == typeof(bool) ? (T)(object)true : default(T)
public T TestMethod()
{
return TrueIfBoolean;
}
}
That way, the boxing/unboxing only happens once. It's also entirely possible that this kind of optimisation is done by the runtime anyway even in your initial code.
Upvotes: -1
Reputation: 499002
This is the only way to handle what you are doing here (returning a non default value for a specific closed generic type).
Upvotes: 4