Search Unity

Visual studio annying behaviour

Discussion in 'Scripting' started by maty1996, Jun 19, 2019.

  1. maty1996

    maty1996

    Joined:
    Nov 7, 2018
    Posts:
    9
    Why is my C# code editor so little intuititve?
    I am aware xValue needs to have an assigned value but I should not apply it by default.

    upload_2019-6-19_10-47-53.png
     
  2. Kwinten

    Kwinten

    Joined:
    Jan 25, 2015
    Posts:
    49
    There's no way for the compiler to know whether or not xValue will actually ever be assigned a value, since it cannot evaluate that either condition (direction == "l" or direction == "r") will ever be true at runtime. Therefore, xValue might be left uninitialized when it is accessed later on.

    In short: always gives your variables a value. It's good practice, will help avoid unexpected behavior, and your compiler / IDE won't complain.
     
    Vryken likes this.
  3. maty1996

    maty1996

    Joined:
    Nov 7, 2018
    Posts:
    9
    ok thanks
     
  4. AndersMalmgren

    AndersMalmgren

    Joined:
    Aug 31, 2014
    Posts:
    5,358
    add else throw new Exception() and it will work

    edit: Your code is not robust because the code can take paths not indented
     
  5. Vryken

    Vryken

    Joined:
    Jan 23, 2018
    Posts:
    2,106
    Programs only do exactly what you tell them to do.
    With the way you have this structured, you are telling the compiler that it is possible for xValue to remain unassigned, therefore it will take this possibility into account.

    The problem here isn't with Visual Studio, it's with the way the logic was written.
     
  6. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    If your direction choices are only "l" or "r", then just do an if check for one of them and make the other an else statement only. Then you'll have an if/else statement which means it will have one value or the other.