What does default(object); do in C#?

Googling is only coming up with the keyword, but I stumbled across some code that says

MyVariable = default(MyObject);

and I am wondering what it means...


  • For a reference-type, it returns null
  • For a value-type other than Nullable<T> it returns a zero-initialized value
  • For Nullable<T> it returns the empty (pseudo-null) value (actually, this is a re-statement of the second bullet, but it is worth making it explicit)
  • The biggest use of default(T) is in generics, and things like the Try... pattern:

    bool TryGetValue(out T value) {
        if(NoDataIsAvailable) {
            value = default(T); // because I have to set it to *something*
            return false;
        }
        value = GetData();
        return true;
    }
    

    As it happens, I also use it in some code-generation, where it is a pain to initialize fields / variables - but if you know the type:

    bool someField = default(bool);
    int someOtherField = default(int)
    global::My.Namespace.SomeType another = default(global::My.Namespace.SomeType);
    

    default keyword will return null for reference types and zero for numeric value types.

    For struct s, it will return each member of the struct initialized to zero or null depending on whether they are value or reference types.

    from MSDN

    Simple Sample code :<br>
        class Foo
        {
            public string Bar { get; set; }
        }
    
        struct Bar
        {
            public int FooBar { get; set; }
            public Foo BarFoo { get; set; }
        }
    
        public class AddPrinterConnection
        {
            public static void Main()
            {
    
                int n = default(int);
                Foo f = default(Foo);
                Bar b = default(Bar);
    
                Console.WriteLine(n);
    
                if (f == null) Console.WriteLine("f is null");
    
                Console.WriteLine("b.FooBar = {0}",b.FooBar);
    
                if (b.BarFoo == null) Console.WriteLine("b.BarFoo is null");
    
            }
        }
    

    OUTPUT:

    0
    f is null
    b.FooBar = 0
    b.BarFoo is null
    

    Specifies the default value of the type parameter.This will be null for reference types and zero for value types.

    See default

    链接地址: http://www.djcxy.com/p/9120.html

    上一篇: C#代码中的问号是什么意思?

    下一篇: 什么是默认(对象); 在C#中做?