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?
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.
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;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With