6

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);
  }
}
Nelson Rothermel
  • 9,436
  • 8
  • 62
  • 81
  • 3
    Generics mean "same code works for multiple types". You want different code for different types, so your use-case is outside the focus of generics. – dtb Nov 08 '12 at 21:19
  • 3
    If you're just going to check the type in the body of the method why make it generic in the first place? – Servy Nov 08 '12 at 21:19
  • Does the .NET runtime not optimize that out? – Travis Gockel Nov 08 '12 at 21:21
  • 1
    @dtb, @Servy: It's something similar to LINQ's `Cast(this IEnumerable source)`, but with a few custom cases such as "Y"/"N" needing manual conversion to true/false. If bool were my own type I could use an explicit operator. All the other types are handled generically. – Nelson Rothermel Nov 08 '12 at 21:31
  • @TravisGockel: That may very well be true, but then it could only do it for the `TestClass` version of the generic. – Nelson Rothermel Nov 08 '12 at 21:38
  • Casting `Func` is the way. See https://stackoverflow.com/questions/45507393 – cactuaroid Jul 31 '21 at 14:52

2 Answers2

4

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

Oded
  • 489,969
  • 99
  • 883
  • 1,009
-1

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.

Tar
  • 429
  • 2
  • 5
  • I don't think the compiler is allowed to optimize away a cast from a value type to `object`. On the other hand, if the cast only happens once, the time wasted is going to be a non-factor. – supercat Dec 18 '12 at 16:59