I was creating an integer and i wanted to instantiate it with 0 before working with.
I wrote firstly
int i = default(int);
then i removed it to replace with the other one which is
int i = 0;
I would like to know if my choice is the best in mini mini performance. Will the default() function increase the instructions at compile time?
No, they are resolved at compile time and produce the same IL. Value types will be 0
(or false
if you have a bool, but that's still 0) and reference types are null
.
Marlon's answer is technically correct, but there should be a clear semantic difference between each option.
int i = 0;
Initializing to literal zero makes semantic sense when you want to do a mathematical operation on the integer, and that operation needs to start with the variable being the specific value of zero. A good example would be creating an index counter variable; you want to start with zero and count up.
int i = default(int);
Setting a variable to its default
value makes sense when you're, for example, creating a class with said variable where you know the variable will be manually set later on in the process. Here's an example (however impractical it may be):
class IntegerClass
{
private int value;
public IntegerClass(int value)
{
this.value = value;
}
public void Reset()
{
this.value = default(int);
}
}
Again, they're technically equal (and in fact will compile to identical CIL) but each provides a different semantic meaning.
Also, using default
could be required to initialize a variable when using generics.
public T SomeOperation<T>()
{
T value = default(T);
this.SomeOtherOperation(ref value);
return T;
}
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