7

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?

15
  • 8
    var message=string.Empty; ? Commented May 25, 2018 at 9:18
  • 3
    "I have to explicitly define it." And what´s the problem with this? var is just a shortcut for the type, so you explicitely define it anyway. It´s clearly stated on MSDN: "The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement". In your case there *is no * expression on the right side. Commented May 25, 2018 at 9:18
  • 5
    Well personally I would consider using var everywhere as bad practicebut you could try write var message = ""; that would define var as string in this case and could work. Commented May 25, 2018 at 9:19
  • 3
    @TheGeneral one reason not to do that is that the definite assignment check can be very useful Commented May 25, 2018 at 9:20
  • 2
    @RandRandom string message; is shorter Commented May 25, 2018 at 9:27

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This however assumes the branches have only a single statement that returns the value.
@HimBromBeere yes, hence "in this case" and "But other than that"
One could always extract a method to circumvent the restriction "single statement per branch": var message = getMessage(error);
5

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

Comments

0

In Python you could do exactly that:

if error:
    message = "there was an error";
else:
    message = "no error";

print(message);

Or even:

message = "there was an error" if error else "no error"

This is possible because Python does not require you to define the variable: the first time you assign a value to a variable, it is created, next times it is modified.

However, this is not the case of C#; as you yourself have confirmed, there are various caveats that do not allow you to code as in Python. First of all, you need to define each variable you are going to use (and its type, but keep reading), and secondly, there is scope. In C# a variable created inside an if branch will not exist further the end of that branch.

And well, then there is var. This is a special shortcut to the type of the value at the right of the assignment operator ("="). It does not mean "I will tell you the type of the variable later". It means "the type of the variable is the same of the expression I'm assigning it to.". In other words, you can only use var when you're assigning a value to a variable at the same time you are defining the variable.

Hope this helps.

3 Comments

The answer to Is it a number or string may be - I don't care - all I care about is it's an "Id Card", whatever that may mean, and I can use it wherever I need to supply an "Id Card". Sometimes the implementation data type is less relevant that the logical type of something, even if you've not modelled logical types in your type system.
The last point about "right" and "misleading" codes doesn't contribute anything to the question. There are already Stack Overflow questions that deal with this situation.
Erased the last paragraph since it seems to be controversial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.