Avoid boxing & unboxing in generic class
Asked Answered
S

2

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);
  }
}
Sama answered 8/11, 2012 at 21:16 Comment(6)
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.Lobate
If you're just going to check the type in the body of the method why make it generic in the first place?Dummy
Does the .NET runtime not optimize that out?Ammadis
@dtb, @Servy: It's something similar to LINQ's Cast<TResult>(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.Sama
@TravisGockel: That may very well be true, but then it could only do it for the TestClass<bool> version of the generic.Sama
Casting Func is the way. See stackoverflow.com/questions/45507393Koumis
D
4

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

Disciplinant answered 8/11, 2012 at 21:18 Comment(1)
This is what I figured since T isn't known at compile time, but I thought I would try. :)Sama
T
-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.

Tektite answered 8/11, 2012 at 22:18 Comment(1)
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.Pneumogastric

© 2022 - 2024 — McMap. All rights reserved.