0

Which C# statement is equivalent to this:

int myInt = new int();

I found this question on http://smarterer.com. The smarterer.com website suggest 3 answers:

  • int myInt = NULL;
  • int myInt;
  • int myInt = 0;

I know the first proposition is incorrect. But what about the two other. My question now is what is the difference between int myInt; and int myInt = 0;? For me it is the same.

Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
  • 1
    first one can't be right cz int is value type and value type can't be null but it can make null if you allow nullable to it like `int? myInt=NULL` – Anik Islam Abhi Nov 20 '14 at 06:31
  • If you look at this: http://stackoverflow.com/questions/5746873/where-and-why-use-int-a-new-int, it should be 'int myInt = 0;' – shrekDeep Nov 20 '14 at 06:33

3 Answers3

9

The second statement depends on context. If it's a field declaration, then it's no different from assigning 0, because type members are always initialized. If it's a local variable, then the second statement doesn't initialize the variable; it would be required for it to be initialized later before you use it.

You can't assign NULL to something of type int, so obviously the first answer isn't the right one. :)

I would choose the third answer, because it is the most reliably like using new int().

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
1

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.

tophallen
  • 1,033
  • 7
  • 12
  • 1
    "However it is best practice to initialize a value on a field" ... I am in trouble with this, because of [performance issues](http://blog.codinghorror.com/for-best-results-dont-initialize-variables/) and [*official* best practice](http://stackoverflow.com/questions/24551/best-practice-initialize-class-fields-in-constructor-or-at-declaration) –  Nov 20 '14 at 07:29
  • well that post also specifies that if your constructor is going to manipulate the value or set it differently than the field initializer would, then you should set it in your constructor - the question only asked about default values.your performance comment is in regards to .NET 2.0 and 1.1 - and yes while it is technically unneeded, there is no performance hit in .NET 4+ because the compiler optimizes that away for you. – tophallen Nov 20 '14 at 07:41
  • "well that post also specifies that if your constructor is going to manipulate the value or set it differently than the field initializer would" - not true: *Creating an object and initializing on definition* –  Nov 20 '14 at 07:45
  • "there is no performance hit in .NET 4+ because the compiler optimizes that away for you" - not true, [just run the code yourself](http://www.codeproject.com/Articles/10439/Gain-performance-by-not-initializing-variables): (Debug) No init: 79,85 - Init on Def: 150,95 - Init in Const: 152,69 | (Release) No init: 69,70 - Init on Def: 77,54 - Init in Const: 143,09 –  Nov 20 '14 at 07:50
  • if you look at the IL - constructor with variable initialization: `IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret` constructor without variable initialization: `IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret` -as you can see it is the same thing - however you will see a hit when setting a _static_ variable on declaration. – tophallen Nov 20 '14 at 08:06
  • in fact, just to further my point, if you decompile an _optimized_ assembly where you set an instance valuetype field to its default value on declaration its not in the code anymore cs file: `class test { public int mynum = 0; }` - decompiled source code: `internal class test { public int mynum; }` – tophallen Nov 20 '14 at 08:12
  • I must deeply appologize for the confusion - now, after the 100th consecutive run, the timings do get (neraly) equal. Just as a side-note (as you already mentioned it): this is only true for release builds. –  Nov 20 '14 at 08:19
  • yes, I specified that in my update, sorry for not clarifying that it would only apply to the release build, but yes, for debug code, un-optimized code and non-primatives, you will see a hit for initializing on the field rather than at use time or in the constructor. - but rather than being a hard and fast rule it is really more a case-by-case rule IMHO – tophallen Nov 20 '14 at 08:30
0

In C# the default value of data type is using by new operator. int myint=new int(); statement is having the same effect as int myInt = 0;

See http://msdn.microsoft.com/en-us/library/83fhsxwc.aspx

leo
  • 8,106
  • 7
  • 48
  • 80
  • This answer is technically a bit confusing (and I suspect *not fully correct*): A default value is depending on the object being a value- or a reference-type, as well as I doubt that the compiler generates a `new T` for every field-declaration (I would need some specs here). –  Nov 20 '14 at 07:38