Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

struct

Say I have a struct

public struct Foo {     ... } 

Is there any difference between

Foo foo = new Foo(); 

and

Foo foo = default(Foo); 

?

like image 519
Bala R Avatar asked Feb 11 '11 21:02

Bala R


2 Answers

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 } 
like image 114
Eric Lippert Avatar answered Sep 28 '22 05:09

Eric Lippert


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.

like image 45
Andrew Hare Avatar answered Sep 28 '22 03:09

Andrew Hare