int
is a struct, so when you define an int in C# it is technically initialized to it's default value (zero). However it is best practice to initialize a value on a field so the most equivalent of the three options you listed is the third one: int myInt = 0
You cannot assign a struct (value type) to null
as it is a non-nullable type.
there are ways to have nullable structs(Nullable<T>
) but that's not what you are asking about.
MSDN on default values
UPDATE:
As my post has some commenters that are sharing mixed results, I figured I would elaborate the percieved performance hit when you initialize valuetypes on delcaration instead of when you need them.
when you optimize your build (no nop
commands in the IL code) you won't see your initialization if you are setting it to the default value, this is the test code:
class initfield
{
public int mynum = 0;
}
class noinitfield
{
public int mynum;
}
and this is the IL for the classes and invoking them (sorry if it is beyond the question scope):
with initialization:
.class private auto ansi beforefieldinit test.initfield
extends [mscorlib]System.Object
{
// Fields
.field public int32 mynum
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x2087
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method initfield::.ctor
} // end of class test.initfield
without initialization:
.class private auto ansi beforefieldinit test.noinitfield
extends [mscorlib]System.Object
{
// Fields
.field public int32 mynum
// Methods
.method public hidebysig specialname rtspecialname
instance void .ctor () cil managed
{
// Method begins at RVA 0x208f
// Code size 7 (0x7)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ret
} // end of method noinitfield::.ctor
} // end of class test.noinitfield
now if you recompile that IL code back into C# for the class that was initializing the field:
internal class initfield
{
public int mynum;
}
as you can see the compiler optimizes the redundant initialization to the default value. Note that this only applies to primitive types, so datetime does not get optimized away. - So in the case of the question asked, int myInt;
and int myInt = 0;
are exactly the same.