596

I'm using reflection to loop through a Type's properties and set certain types to their default. Now, I could do a switch on the type and set the default(Type) explicitly, but I'd rather do it in one line. Is there a programmatic equivalent of default?

1
  • This should work: Nullable<T> a = new Nullable<T>().GetValueOrDefault();
    – dancer42
    Jun 5, 2020 at 2:24

16 Answers 16

805
  • In case of a value type use Activator.CreateInstance and it should work fine.
  • When using reference type just return null
public static object GetDefault(Type type)
{
   if(type.IsValueType)
   {
      return Activator.CreateInstance(type);
   }
   return null;
}

In the newer version of .net such as .net standard, type.IsValueType needs to be written as type.GetTypeInfo().IsValueType

17
  • 24
    This will return a boxed value type and therefore isn't the exact equivalent of default(Type). However, it's as close as you are going to get without generics. Jul 7, 2011 at 14:27
  • 9
    So what? If you find a type which default(T) != (T)(object)default(T) && !(default(T) != default(T)) then you have an argument, otherwise it does not matter whether it is boxed or not, since they are equivalent. Oct 11, 2012 at 6:14
  • 7
    The last piece of the predicate is to avoid cheating with operator overloading... one could make default(T) != default(T) return false, and that is cheating! =) Oct 11, 2012 at 6:16
  • 5
    This helped me a lot, but I thought I should add one thing that might be useful to some people searching this question - there's also an equivalent method if you wanted an array of the given type, and you can get it by using Array.CreateInstance(type, length). Jun 30, 2013 at 1:34
  • 4
    Don't you worry about creating an instance of an unknown value type? This may have collateral effects.
    – ygormutti
    Oct 14, 2013 at 9:08
117

Why not call the method that returns default(T) with reflection ? You can use GetDefault of any type with:

    public object GetDefault(Type t)
    {
        return this.GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this, null);
    }

    public T GetDefaultGeneric<T>()
    {
        return default(T);
    }
7
  • 10
    This is brilliant because it's so simple. While it's not the best solution here, it's an important solution to keep in mind because this technique can be useful in a lot of similar circumstances. Feb 17, 2013 at 12:45
  • If you call the generic method "GetDefault" instead (overloading), do this: this.GetType().GetMethod("GetDefault", new Type[0]).<AS_IS> May 7, 2013 at 10:50
  • 4
    Keep in mind, this implementation is much slower (due to reflection) than the accepted answer. It's still viable, but you'd need to setup some caching for the GetMethod()/MakeGenericMethod() calls to improve performance.
    – Doug
    Nov 2, 2015 at 16:33
  • 2
    It is possible that the type argument is void. E.g. MethodBase.ResultType() of a void method will return a Type object with Name "Void" or with FullName "System.Void". Therefore I put a guard: if (t.FullName=="System.Void") return null; Thanks for the solution.
    – Valo
    Mar 23, 2017 at 2:24
  • 12
    Better use nameof(GetDefaultGeneric) if you can, instead of "GetDefaultGeneric"
    – Mugen
    Oct 10, 2017 at 10:42
98

You can use PropertyInfo.SetValue(obj, null). If called on a value type it will give you the default. This behavior is documented in .NET 4.0 and in .NET 4.5.

1
  • 8
    For this specific question - looping trough a type's properties AND setting them to "default" - this works brilliantly. I use it when converting from a SqlDataReader to an object using reflection. Jun 23, 2013 at 9:13
58

If you're using .NET 4.0 or above and you want a programmatic version that isn't a codification of rules defined outside of code, you can create an Expression, compile and run it on-the-fly.

The following extension method will take a Type and get the value returned from default(T) through the Default method on the Expression class:

public static T GetDefaultValue<T>()
{
    // We want an Func<T> which returns the default.
    // Create that expression here.
    Expression<Func<T>> e = Expression.Lambda<Func<T>>(
        // The default value, always get what the *code* tells us.
        Expression.Default(typeof(T))
    );

    // Compile and return the value.
    return e.Compile()();
}

public static object GetDefaultValue(this Type type)
{
    // Validate parameters.
    if (type == null) throw new ArgumentNullException("type");

    // We want an Func<object> which returns the default.
    // Create that expression here.
    Expression<Func<object>> e = Expression.Lambda<Func<object>>(
        // Have to convert to object.
        Expression.Convert(
            // The default value, always get what the *code* tells us.
            Expression.Default(type), typeof(object)
        )
    );

    // Compile and return the value.
    return e.Compile()();
}

You should also cache the above value based on the Type, but be aware if you're calling this for a large number of Type instances, and don't use it constantly, the memory consumed by the cache might outweigh the benefits.

8
  • 6
    Performance for 'return type.IsValueType ? Activator.CreateInstance(type) : null;' is 1000x faster than e.Compile()();
    – Cyrus
    Aug 31, 2014 at 19:48
  • 2
    @Cyrus I am fairly sure it would be the other way round if you cache the e.Compile(). That's the whole point of expressions.
    – nawfal
    Jul 5, 2016 at 8:38
  • 2
    Ran a benchmark. Obviously, the result of e.Compile() should be cached, but assuming that, this method is roughly 14x as fast for e.g. long. See gist.github.com/pvginkel/fed5c8512b9dfefc2870c6853bbfbf8b for the benchmark and results. Jan 30, 2018 at 13:59
  • 4
    Out of interest, why cache e.Compile() rather than e.Compile()()? i.e. Can a type's default type change at runtime? If not (as I believe to be the case) you can just store cache the result rather than the compiled expression, which should improve performance further.
    – JohnLBevan
    Oct 2, 2018 at 13:19
  • 4
    @JohnLBevan - yes, and then it won't matter what technique you use to get the result - all will have extremely fast amortised performance (a dictionary lookup). Oct 2, 2018 at 13:36
41

Why do you say generics are out of the picture?

    public static object GetDefault(Type t)
    {
        Func<object> f = GetDefault<object>;
        return f.Method.GetGenericMethodDefinition().MakeGenericMethod(t).Invoke(null, null);
    }

    private static T GetDefault<T>()
    {
        return default(T);
    }
4
  • Cannot resolve symbol Method. Using a PCL for Windows.
    – Cœur
    Jun 14, 2014 at 13:43
  • 1
    how expensive is it to create the generic method at run time, and then use it several thousand times in a row?
    – C. Tewalt
    Sep 3, 2014 at 17:11
  • 1
    I was thinking about something like this. Best and most elegant solution for me. Works even on Compact Framework 2.0. If you are worried about performance, you can always cache generic method, can't you?
    – Bart
    Oct 27, 2015 at 20:26
  • This solution suits exactly! Thanks! Oct 12, 2018 at 13:12
28

This is optimized Flem's solution:

using System.Collections.Concurrent;

namespace System
{
    public static class TypeExtension
    {
        //a thread-safe way to hold default instances created at run-time
        private static ConcurrentDictionary<Type, object> typeDefaults =
           new ConcurrentDictionary<Type, object>();

        public static object GetDefaultValue(this Type type)
        {
            return type.IsValueType
               ? typeDefaults.GetOrAdd(type, Activator.CreateInstance)
               : null;
        }
    }
}
3
  • 3
    A short hand version of the return: return type.IsValueType ? typeDefaults.GetOrAdd(type, Activator.CreateInstance) : null; Jan 23, 2013 at 14:08
  • 4
    What about mutable structs? Do you know that it is possible (and legal) to modify fields of a boxed struct, so that the data change?
    – IS4
    Apr 26, 2015 at 19:23
  • @IllidanS4 as the method's name implies this is only for default ValueType's values.
    – aderesh
    Jan 24, 2018 at 16:21
10

There are a couple answers here that use Activator.CreateInstance. However, since those answers were made, C# and .NET made changes that allow users to define structs with parameterless constructors (documentation link). Activator.CreateInstance will execute such a parameterless constructor if defined, and you will no longer get the default instance.

Instead you can use RuntimeHelpers.GetUninitializedObject, like so:

//using System.Runtime.CompilerServices
public static object GetDefault(Type type)
{
    // it's very important to check IsValueType before calling GetUninitializedObject
    // GetUninitializedObject is valid for reference types, but it will not return null
    if (type.IsValueType)
    {
        return RuntimeHelpers.GetUninitializedObject(type);
    }
    return null;
}

Another option, which you can do as a single-liner, is use Array.CreateInstance:

// works for both reference types and value types
static object GetDefault(Type type) => Array.CreateInstance(type, 1).GetValue(0);

Edit: Previous answer suggested using FormatterServices.GetUninitializedObject but this has been deprecated starting in .NET 8.

1
7

The chosen answer is a good answer, but be careful with the object returned.

string test = null;
string test2 = "";
if (test is string)
     Console.WriteLine("This will never be hit.");
if (test2 is string)
     Console.WriteLine("Always hit.");

Extrapolating...

string test = GetDefault(typeof(string));
if (test is string)
     Console.WriteLine("This will never be hit.");
4
  • 16
    true, but that holds for default(string) as well, as every other reference type...
    – TDaver
    Jan 21, 2011 at 14:12
  • string is an odd bird - being a value type that can return null as well. If you want the code to return string.empty just add a special case for it Jul 7, 2011 at 7:09
  • 16
    @Dror - string is an immutable reference type, not a value type.
    – ljs
    Aug 18, 2011 at 16:01
  • @kronoz You're right - I meant that string can be handled by returning string.empty or null according to need. Aug 21, 2011 at 6:40
5

I do the same task like this.

//in MessageHeader 
   private void SetValuesDefault()
   {
        MessageHeader header = this;             
        Framework.ObjectPropertyHelper.SetPropertiesToDefault<MessageHeader>(this);
   }

//in ObjectPropertyHelper
   public static void SetPropertiesToDefault<T>(T obj) 
   {
            Type objectType = typeof(T);

            System.Reflection.PropertyInfo [] props = objectType.GetProperties();

            foreach (System.Reflection.PropertyInfo property in props)
            {
                if (property.CanWrite)
                {
                    string propertyName = property.Name;
                    Type propertyType = property.PropertyType;

                    object value = TypeHelper.DefaultForType(propertyType);
                    property.SetValue(obj, value, null);
                }
            }
    }

//in TypeHelper
    public static object DefaultForType(Type targetType)
    {
        return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
    }
3

Equivalent to Dror's answer but as an extension method:

namespace System
{
    public static class TypeExtensions
    {
        public static object Default(this Type type)
        {
            object output = null;

            if (type.IsValueType)
            {
                output = Activator.CreateInstance(type);
            }

            return output;
        }
    }
}
3

The Expressions can help here:

    private static Dictionary<Type, Delegate> lambdasMap = new Dictionary<Type, Delegate>();

    private object GetTypedNull(Type type)
    {
        Delegate func;
        if (!lambdasMap.TryGetValue(type, out func))
        {
            var body = Expression.Default(type);
            var lambda = Expression.Lambda(body);
            func = lambda.Compile();
            lambdasMap[type] = func;
        }
        return func.DynamicInvoke();
    }

I did not test this snippet, but i think it should produce "typed" nulls for reference types..

1
  • 1
    "typed" nulls - explain. What object are you returning? If you return an object of type type, but its value is null, then it does not - cannot - have any other information other than that it is null. You can't query a null value, and find out what type it supposedly is. If you DON'T return null, but return .. I don't know what .., then it won't act like null. Feb 6, 2018 at 2:57
3

Slight adjustments to @Rob Fonseca-Ensor's solution: The following extension method also works on .Net Standard since I use GetRuntimeMethod instead of GetMethod.

public static class TypeExtensions
{
    public static object GetDefault(this Type t)
    {
        var defaultValue = typeof(TypeExtensions)
            .GetRuntimeMethod(nameof(GetDefaultGeneric), new Type[] { })
            .MakeGenericMethod(t).Invoke(null, null);
        return defaultValue;
    }

    public static T GetDefaultGeneric<T>()
    {
        return default(T);
    }
}

...and the according unit test for those who care about quality:

[Fact]
public void GetDefaultTest()
{
    // Arrange
    var type = typeof(DateTime);

    // Act
    var defaultValue = type.GetDefault();

    // Assert
    defaultValue.Should().Be(default(DateTime));
}
0
0

According to one of Microsoft's issues the best alternative of

type.IsValueType ? Activator.CreateInstance(type) : null

is the following:

Serialization.FormatterServices.GetUninitializedObject(Type type)

Link to discussion

-1
 /// <summary>
    /// returns the default value of a specified type
    /// </summary>
    /// <param name="type"></param>
    public static object GetDefault(this Type type)
    {
        return type.IsValueType ? (!type.IsGenericType ? Activator.CreateInstance(type) : type.GenericTypeArguments[0].GetDefault() ) : null;
    }
1
  • 2
    Doesn't work for Nullable<T> types: it doesn't return the equivalent of default(Nullable<T>) which should be null. Accepted answer by Dror works better.
    – Cœur
    Jun 16, 2014 at 0:11
-1

This should work: Nullable<T> a = new Nullable<T>().GetValueOrDefault();

1
  • 1
    it will work only for struct, as Nullable has generic constraint on T: where T : struct Dec 23, 2020 at 13:30
-1

If you already create an object, you can try...

var yourObj = new yourObj();
var properties = yourObj.GetType().GetProperties();

foreach (var p in properties)
{
    // you can get default value for each property
    var defaultValue = p.GetValue(yourObj, null);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.