Is there a way to use var when variable is defined in an if/else statement?

  • A+
Category:Languages

I use var whenever I can since it's easier not to have to explicitly define the variable.

But when a variable is defined within an if or switch statement, I have to explicitly define it.

string message; //var message; <--- gives error if (error) {     message = "there was an error"; } else {     message = "no error"; }  Console.WriteLine(message); 

Is there a way to use var even if the variable is defined inside an if or switch construct?


You can't and you can confirm by looking at documentation:

The following restrictions apply to implicitly-typed variable declarations:

var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

So to use var you must always initialize it in the same statement according to the rules above.

Initializing it to some default value does not have the same semantics as unitialized variable. For example:

string message; if (error) {     message = "there was an error"; } else {     // forgot to assign here } // Compiler error, use of potentially uninitialized variable Console.WriteLine(message); 

But

var message = ""; if (error) {     message = "there was an error"; } else {     // forgot to initialize } // all fine Console.WriteLine(message); 

So, just use string message;.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: