Why Can Var Not Be Used As A Class Variable? RRS feed


All replies

  • Strict typing?

    • Marked as answer by IndigoMontoya Tuesday, April 21, 2015 2:19 PM
    Tuesday, April 21, 2015 2:01 PM
  • Strict typing?

    Ya lost me their...
    Tuesday, April 21, 2015 2:10 PM
  • >>And why can it not be declared as a class variable?

    Because the compiler must be able to determine the type of the var variable and the C# compiler cannot do this for fields of type var.

    A var variable is as strongly typed just as if you would had declared the type yourself explicitly but the compiler determines the type for you.

    Eric Lippert from the  C# compiler team has provided a longer answer here if you are interested:

    Why no var on fields?:

    >>WHat's so bad about using var?

    Nothing really. As mentioned the variable is still strongly typed. You might argue that it gets a bit harder to read the code and for a developer to determine the actual type of a var variable compared to an explicitly typed variable though.

    Hope that helps.

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't post several questions in the same thread.

    Tuesday, April 21, 2015 2:22 PM
  • Strict typing?

    Isn't strictly typed? It just safes you from typing it yourself explictly and you can have the correct type be determined automatically.


    Tuesday, April 21, 2015 2:24 PM