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!
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.
Variables of type "int" have a default value of 0.
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.
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.
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.
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
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.
Another factor could be in the future if (default) definition has been changed in the compiler then your project might break.
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