39

Just curious, what is the difference between:

int A = 100;

and

int A = new int();  

I know new is used to allocate memory on the heap..but I really do not get the context here.

Brandon
  • 68,708
  • 30
  • 194
  • 223
Miriah
  • 399
  • 1
  • 3
  • 3
  • To be simple enough..., int A=100; is simply declaring an int var A and initialising it to 100.., whereas int A= new int(); is an error .,Although it could be.. int *A = new int(); which means create space for an int on stack put 0 in it and return address of that int to integer pointer,i.e A – eRaisedToX Aug 09 '16 at 16:13
  • 2
    @eRaisedToX It is not an error to use new operator with a value type. https://stackoverflow.com/questions/5563774/dilemma-with-using-value-types-with-new-operator-in-c-sharp It basically does nothing observable. And the tag is for C# not C++. – Tanveer Badar Aug 03 '17 at 11:54

10 Answers10

36
static void Main()
{
    int A = new int();
    int B = default(int);
    int C = 100;
    Console.Read();
}

Is compiled to

.method private hidebysig static void  Main() cil managed
{
  .entrypoint
  // Code size       15 (0xf)
  .maxstack  1
  .locals init ([0] int32 A,
           [1] int32 B,
           [2] int32 C)
  IL_0000:  nop
  IL_0001:  ldc.i4.0
  IL_0002:  stloc.0
  IL_0003:  ldc.i4.0
  IL_0004:  stloc.1
  IL_0005:  ldc.i4.s   100
  IL_0007:  stloc.2
  IL_0008:  call       int32 [mscorlib]System.Console::Read()
  IL_000d:  pop
  IL_000e:  ret
} // end of method Program::Main

As you can see first one just initialize it and second one is just the same and third one initialize and set to 100. As for the IL code generated, they both get initialized in a single line.

so

int A = new int();

Is the same as

int A = default(int);
Picrofo Software
  • 5,475
  • 3
  • 23
  • 37
Aliostad
  • 80,612
  • 21
  • 160
  • 208
22

Difference?

the latter ends with A being 0, not 100.

When?

Pretty much never. Maybe in some generated code it is simpler to use the new TypeName() syntax, but default(TypeName) would be preferred even then.

And new does not "allocate memory on the heap". It initializes an instance; that is all.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • SO there is no meaning in the new keyword? – Miriah Apr 21 '11 at 16:19
  • Unless you want an instance of the object/structure and not just the default/null value. – Matthew Whited Apr 21 '11 at 16:20
  • 1
    @Miriah - there is meaning: it means we want to initialize a new object or value; it just doesn't strictly mean anything to do with heap or stack. Note that `new` has an alternative usage (as a keyword) in method hiding. Completely unrelated, but it exists. – Marc Gravell Apr 21 '11 at 18:16
10

I strongly recommend that you read this article from dotnet mob: http://codaffection.blogspot.in/2015/02/difference-between-declarations-int-i.html

int A = 100; //Initialises A to 100 manually

Suppose you declare an integer as

int A;

For further operations on A, you need to initialise A with an integer value, otherwise the compiler shows

use of unassigned local variable

To declare A as follows

int A = new int(); //A initialised to 0 (default value of int)

allows for further operations on A without a manual initialisation - I think you get my point now.


Now let's discuss using new ().

Use of new doesn't mean memory will be allocated on the heap; if A is a local variable (e.g. in a method) it will be allocated memory on the stack. If A is a member of a class however, then memory will be allocated on the heap when an instance of the class is created.

Point to be remembered: if A is static, it will always be on stack memory!

Adrian
  • 33
  • 6
Shamseer K
  • 4,964
  • 2
  • 25
  • 43
  • I like this explanation, but what then is the difference between initializing a variable with "int x = 0" versus"int x = new()"? – Stokely Aug 22 '17 at 22:01
  • @Stokely int x= 0 vs int x = new int(); no difference in both case x will initialised to zero. – Shamseer K Aug 23 '17 at 04:34
9
int A=100;

Allocates an int on the stack and sets its value to 100.

int A=new int();

Allocates an int on the stack (yes, value types are always allocated on the stack, even with the new keyword) and sets its value to the default, that is, 0.

user703016
  • 37,307
  • 8
  • 87
  • 112
  • 2
    The "value types on the stack" is misleading. For example, in an array-of-structs, or as a field on a class. It also depends how you count a "unit on the stack then copy" – Marc Gravell Apr 21 '11 at 17:22
  • 5
    you said *always*... always is not "this precise case" – Marc Gravell Apr 21 '11 at 18:14
  • 2
    Always is incorrect, if the int is a local var, then it will be on the stack, but if it's an instance field then it will be on the heap. – David Klempfner Feb 21 '14 at 01:03
6

I saw it from another link:

MSDN says "The new operator is also used to invoke the default constructor for value types."

Inside a method:

  • int x;: allocates an int on stack and does not initialize it.
  • int x=5;: allocates an int on stack and sets it to 5;
  • int x=new int();: allocates an int on stack and sets it to 0;
  • int x=new int(5);: does not compile.

http://msdn.microsoft.com/en-us/library/fa0ab757.aspx

thkala
  • 84,049
  • 23
  • 157
  • 201
Howard
  • 3,638
  • 4
  • 32
  • 39
2
myInt = new int();  // Invoke default constructor for int type.

This statement is equivalent to the following statement:

myInt = 0;         // Assign an initial value, 0 in this example.

Using the new operator calls the default constructor of the specific type and assigns the default value to the variable. The default value of an integer is 0 BTW.

The difference is that you can't initialize and set anything but the default value value using the new operator.

rucsi
  • 516
  • 2
  • 7
  • They are not the same. See my comments. – Aliostad Apr 21 '11 at 16:43
  • Initializing Value Types : http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx also in my reading, as 0 is the default value of an int, that's why myInt = default(int) and myInt = 0 are going to be the same. – rucsi Apr 26 '11 at 14:41
  • Thanks for confirming my suspicions about using "new" and "default". Their use is pointless. It seems its much better to always instantiate a value type to a default value you choose, even if its 0, so its always available. You also avoid confusion as to what its custom default should be. – Stokely Aug 22 '17 at 22:04
1

I don't think it is necessary to add new on int(because int has default memory size).. new is used when we have a user-defined class of which we instantiate an object..

public static Main()
{
  Cat cat1=new Cat();
}

Public class Cat
{
  public bool Sex
  public string Name
}

Now compiler will allocate that much memory to cat1(memory size which is defined in class Cat)

Oniel Telies
  • 155
  • 2
  • 14
0

If you are using the int as a field in your class, you might even say simply int x; - since int is a value type it cannot be null and therefore gets its default value - i.e. 0.

Jasper
  • 1
0

I end up discovering my problem

I was modifying the values but not the Object

This is the proper way to do it :

 public ActionResult ChangeDefaultUserLockingSetting(int PasswordAttempts, int DefaultLockingTime)
        {
            var defaultAccountSettings = new DefaultAccountSettingsDataContext();

            var accountSettings = defaultAccountSettings.DefaultAccountSettings.First(u => u.id == 1);


            accountSettings.DefaultAccountLockoutTimeSpan = DefaultLockingTime;
            accountSettings.MaxFailedAccessAttemptsBeforeLockout = PasswordAttempts;

            defaultAccountSettings.SubmitChanges();
            return View("Index", loadAdministrationViewModel());
        }
napi15
  • 2,354
  • 2
  • 31
  • 55
0

"int" is a value type, so neither expression will allocate memory on the managed heap. The first statement will initialize A to the literal you specify. The second statement will leave A at a default value.

Ed Noepel
  • 425
  • 3
  • 9