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);
}
}
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.”
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)
This is the only way to handle what you are doing here (returning a non default value for a specific closed generic type).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With