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

后端 未结 9 2315
误落风尘
误落风尘 2020-11-28 03:03

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

MyVariable = default(MyObject);

and I am wondering

9条回答
  •  再見小時候
    2020-11-28 03:32

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

    For structs, 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 :
    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
    

提交回复
热议问题