0

Let's say I have this function which instantiates a new variable with default/empty value for any type

public static T GetDefault<T>() where T : new() //body of this method is the question
{
    T t = new T();
    return t;
}

The problem with the above function is when I have something like int? for T. Because if I have

int? t = new int?();

t will be null! I do not want this to happen, instead I want the default value of int to be returned which is 0.

To solve this, I can have different overloads of GetDefault function for int?, bool? etc but that's not elegant. I can also check internally in the function if type is int? or bool? etc, but how would I go about instantiating it's base type?

Or the question boils down to how to identify if T is nullable struct and accordingly how to instantiate the nullable struct..

nawfal
  • 70,104
  • 56
  • 326
  • 368
  • possible duplicate of [Creating a nullable object via Activator.CreateInstance returns null](http://stackoverflow.com/questions/8691601/creating-a-nullable-object-via-activator-createinstance-returns-null) – nawfal Apr 25 '13 at 12:16

1 Answers1

3
Type realType = Nullable.GetUnderlyingType(typeof(T));
t = (T)Activator.CreateInstance(realType ?? typeof(T));
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Nice solution! Except that `new T()` would be marginally faster for structs. Doesn't matter, this looks elegant :) – nawfal Oct 14 '12 at 23:30
  • @nawfal: Actually, I'm pretty sure that's false. `new T()` compiles to `Activator.CreateInstance()`, which in turn calls `rt.CreateInstanceDefaultCtor(...)`. `Activator.CreateInstance(Type)` calls a very similar overload. _Disclaimer: I haven't measured it_. – SLaks Oct 15 '12 at 22:03
  • I did tell it was only for structs. new T() performs better. But for nullable types, its all the same.. – nawfal Oct 16 '12 at 00:27
  • May be `CreateInstance` for structs were slower since it involved unboxing when cast to `int`. Have a look at related question http://stackoverflow.com/questions/6069661/does-system-activator-createinstancet-have-performance-issues-big-enough-to-di – nawfal Feb 21 '13 at 14:09