Question

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);
  }
}
Was it helpful?

Solution

This is the only way to handle what you are doing here (returning a non default value for a specific closed generic type).

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top