Search code examples
c#memoryintegernew-operatorallocation

C# creating variables, Int a = new int();


What is the difference between:

a) int A = new int();

and

b) int A = 0;


Solution

  • When you create an int, it is assumed that you will be assigning an integer value to it, so int A = 0; effectively creates a new instance of an int, and assigns it the value 0 as it's what you have told it to assign.

    Any value you enter, assuming it is indeed an int, can be assigned to A as its value.

    int A = new int() will create a new instance of int, but it will call the default constructor as you haven't specified what you want to assign as the value of A. As a result, it will assign A the default value of 0.

    This is expanded much further in this answer - Where and why use int a=new int?

    Something that is worth keeping in mind is that when you're uncertain about fundamental behaviour in a programming language, it's better to look up getting started guides or white papers on the language to find out why things work the way they do.

    Questions on SO will usually get more responses if you can ask a question about how some behaviour works, explaining why you're stuck and what you have done to solve the issue.

    A lot of members are incredibly knowledgable, but many are industry professionals and tend to have limited free time. If you can show what steps you've taken to work out the solution before posting, members are often more likely to put the time aside to come up with an answer.