Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 462
Edward Tanguay Avatar asked May 25 '18 09:05

Edward Tanguay


2 Answers

No. You could use a conditional in this case, though:

var message = error ? "there was an error" : "no error";

But other than that: no. You'll need to specify the type, or use an initial explicit value. I advise against the latter as it removes the definite assignment check.

like image 164
Marc Gravell Avatar answered Nov 04 '22 18:11

Marc Gravell


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;.

like image 40
Evk Avatar answered Nov 04 '22 18:11

Evk