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.

Szkaplerny
  • 49
  • 3
  • 11

2 Answers2

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.

Community
  • 1
  • 1
JimBobBennett
  • 2,149
  • 14
  • 11
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.

D Stanley
  • 149,601
  • 11
  • 178
  • 240