Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid boxing & unboxing in generic class

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);
  }
}
like image 935
Nelson Rothermel Avatar asked Nov 08 '12 21:11

Nelson Rothermel


People also ask

What are the negative effects of boxing?

Neurological trauma from boxing has three primary manifestations: (i) acute neurologic injuries; (ii) persistent groggy states and the post-concussion syndrome; and (iii) chronic traumatic encephalopathy (CTE), commonly referred to as the “punch-drunk syndrome” or “dementia pugilistica.”

Is any way we can avoid the boxing and unboxing?

How to prevent boxing & unboxing: Use ToString method of numeric data types such as int, double, float etc. Use for loop to enumerate on value type arrays or lists (do not use foreach loop or LINQ queries) Use for loop to enumerate on characters of string (do not use foreach loop or LINQ queries)


1 Answers

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

like image 158
Oded Avatar answered Sep 24 '22 07:09

Oded