Avoid boxing & unboxing in generic class

boxing, c#, generics, unboxing

Solution

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

Problem

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

Original source

Related problems