Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between default(int) vs int = 0

Tags:

c#

anyone knows if exists any difference between declare an integer variable using:

var i = default(int)

vs

var i = 0;

Maybe a small performance difference or other differences?

Thanks to all!

like image 369
Julito Avellaneda Avatar asked Sep 11 '14 02:09

Julito Avellaneda


People also ask

What is default int in C#?

int a = default(int); Beginning with C# 7.1, you can use the default literal to initialize a variable with the default value of its type: C# Copy.

Does int have a default value?

Variables of type "int" have a default value of 0.

What is the meaning of default value?

Default values, in the context of databases, are preset values defined for a column type. Default values are used when many records hold similar data.


5 Answers

Effectively, there is no difference. According to MSDN

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

int is a value type, so the expression will resolve to 0.

I would perform the explicit 0 assignment as its a lot more readable.

like image 109
BradleyDotNET Avatar answered Oct 24 '22 09:10

BradleyDotNET


Here's the IL for the var i = default(int) code:

IL_0001:  ldc.i4.0    
IL_0002:  stloc.0     // i

Here's the IL for the var i = 0; code:

IL_0001:  ldc.i4.0    
IL_0002:  stloc.0     // i

Seems like it boils down to personal preference.

like image 27
Enigmativity Avatar answered Oct 24 '22 08:10

Enigmativity


There is no difference between the two.
In C# there are facilities provided for different situations. This doesn't imply using them in all situations regardless of their logical reason behind it.
For example default is most common in generics since In generic classes and methods, one issue that arises is how to assign a default value to a parameterized type T when you do not know the following in advance.
Although you can use it with primitive types such as int, but you are not suggested to do so, its whole reason of existence is something else.
Use the later one as it is more readable and logical.
You may also want to see this link on default

like image 27
Hossein Avatar answered Oct 24 '22 08:10

Hossein


In terms of functionality, no, there is no difference as 0 is the default value for type int.

In terms of performance, I'm pretty sure that default(int) is replaced by 0 during compile time so the only slight performance hit can happen during compile time, but not runtime.

like image 3
mostruash Avatar answered Oct 24 '22 09:10

mostruash


Another factor could be in the future if (default) definition has been changed in the compiler then your project might break.

like image 3
codebased Avatar answered Oct 24 '22 09:10

codebased