+ 1

Challenge question : Why is the output 5

I came across this challenge question. The answer is 5; Why is the answer 5 and not 4; Test() is the constructor, so after it the Test-object is created, a will be assigned to 3 and then be incremented to 4 ? static void Main(string[] args) { Test t = new Test(); Console.Write(t.a); } public class Test { public int a=5; public Test() { int a = 3; a++; } }

20th Sep 2017, 9:43 PM
sneeze
sneeze - avatar
3 Answers
+ 8
int a = 3; creates a new int primitive and does not references the one in the Test class (3 lines above) if you were to replace int a = 3; with this.a = 3; you then would get a result of 4 as it will reference the a primitive of the class and won't be a new one so when you call the Console.Write method, you actually print the public int a = 5; which never changed.
20th Sep 2017, 9:52 PM
Burey
Burey - avatar
+ 2
I guess "t.a" means calling the property not the local variable inside the constructor.
20th Sep 2017, 9:56 PM
Joefrey Racal Ramos
Joefrey Racal Ramos - avatar