Say I have a struct
public struct Foo { ... }
Is there any difference between
Foo foo = new Foo();
and
Foo foo = default(Foo);
?
You might wonder why, if they are exactly the same, there are two ways to do the same thing.
They are not quite the same because every reference type or value type is guaranteed to have a default value but not every reference type is guaranteed to have a parameterless constructor:
static T MakeDefault<T>() { return default(T); // legal // return new T(); // illegal }
No, both expressions will yield the same exact result.
Since structs cannot contain explicit parameterless constructors (i.e. you cannot define one yourself) the default constructor will give you a version of the struct with all values zero'd out. This is the same behavior that default
gives you as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With