1

I've problem with understanding code. I'm learning coding in Unity, I have a really little knowlegde about C#, but something caught my attention - in course we first declarate variable int (without setting any value) and then we use it in if statement.

I read here that using uninitialized variables in C# is not allowed. And I checked it in another project on my own. I was thinking it is because of structure (not class) but I have no clue why it would have impact on variables...

Because there is a lot of needless code I will put it on outside (pastebin) server - the code with this variable are set as comments (for better visibility).

Here I will put only these fragments (for people who don't want to waste time to going through whole mess).

  1. private int questionsFinished;

  2. [...] if(questionsFinished < questionNumbersChoosen.Length - 1) { moveToNextQuestion(); questionsFinished++; }

  3. public void moveToNextQuestion() { assignQuestion(questionNumbersChoosen[questionNumbersChoosen.Length - 1 - questionsFinished]); }

I just don't understand why it's working - the variable has no value, yes? Thank you guys in advance.

2
  • Member variables of type int automatically get initialized to 0 if it is not explicitly initialized to another value
    – user469104
    Apr 6, 2016 at 21:00
  • what's wrong with my question so it is downvoted?
    – Szkaplerny
    Apr 6, 2016 at 21:06

2 Answers 2

2

questionsFinished does have a value - because it is a field on your class. Fields are initialised to their default value unless you explicitly set them. In this case questionsFinished will be initialised to 0 as it is an int. Numerical types default to 0, bools to false, strings and reference types default to null, structs to their default value depending on their constructors.

By variables they mean local variables inside your method.

Great explanation from Eric Lippert here:

Why do local variables require initialization, but fields do not?

Essentially - if you don't initialise a local variable it is most likely to be a bug and the compiler is helping you out. Fields having their default value is a popular case so the compiler assumes you did it on purpose and doesn't raise a bug.

2
  • this is more accurate answer after the @user469104 comment. Only can add that for value type int default value is 0, if it was reference type then null
    – Vladimir
    Apr 6, 2016 at 21:07
  • Thanks @Vladimir - updated Apr 6, 2016 at 21:12
1

questionsFinished is a field, not a local variable, so it does not need to be initialized. It is good practice to do so, however.

In general the compiler cannot tell deterministically whether or not a field will be set to a value before use (since public fields could be initialized externally), so it does not generate an error.

Fields are initialized to their default value, which is 0 for int.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.