C# struct new StructType() vs default(StructType)

后端 未结 5 1488
情深已故
情深已故 2021-01-31 01:44

Say I have a struct

public struct Foo
{
    ...
}

Is there any difference between

Foo foo = new Foo();

and <

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 02:16

    default keyword is useful when you do not know exact type and it works not only for structs, for example in generics:

    T FirstOrDefault(IEnumerable source)
    {
        if (...source is empty...) return default(T);
    }
    

    This will return null for reference types, default value for primitive types(0 for numbers, false for bool), defaultly inialized structure, etc ...

    When type is known at compile-time it makes no sense to use default, you can use new Foo() instead

提交回复
热议问题