Avoid Boxing and Unpacking in the Family Class

Below is a short code illustrating 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); } } 
+6
source share
2 answers

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

+4
source

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; } } 

Thus, boxing / unpacking occurs only once. It is also quite possible that such optimization is performed in any case, even in the source code.

0
source

All Articles