maxp
maxp

Reputation: 25141

Declaring a variable inside an equality operation possible?

Very quick question - whilst the following is possible in C#:

var a = new []{"hello"};
string[] b;
if ((b=a)!=null) { ... }

the following is not:

var a = new []{"hello"};
if ((string[] b=a)!=null) { ... }

Just wanted to confirm that I wasnt doing anything wrong in the second example and something along those lines are not possible. (In the similiar way aspects from the second example might be posible inside a using().

Upvotes: 0

Views: 61

Answers (3)

Jodrell
Jodrell

Reputation: 35716

Wait,

To simplify your question.

You can do,

var a = 0;
var b = 1;
var c = a = b;

but you can't do,

var x = 0;
var x = var y = 1;

this seems obvious.

The assign of a value returns the assigned value. The instantiation or initialisation of a variable does not.

However, you do allude to cases where we can instantiate in a block declaration.

using(var x = new SomeIDisposable(...

foreach(var y in SomeIEnumerable...

There are certainly others. These are essentially syntactic sugar. The designers of c# have corrupted its semantic purity to make it easier to use. I assume they have not done this generally, for all instantiations, because in thier opinion, it leads to messy code.

Upvotes: 1

Tigran
Tigran

Reputation: 62246

Yes, correct, you can not do like that.

The reason is simply that the declaration of the variable can not be a part of conditional statement, also because, even if it would be possible, the variable will be allocated either condition validate to true or validates to false. Check an IL and you will see.

So from the clear and understandable code point of view, it's correct to pretend from the coder to write

string[] b;
if ((b=a)!=null) { ... }

Upvotes: 1

BuddhiP
BuddhiP

Reputation: 6451

This is not possible, since in c# variable declaration is a 'statement', not an expression. Statements do not yield a value, therefore I do not think you can use it in a expression.

But the assignment, which you use in the second first form is an 'expression' which yield a result (value of a in this case), which can be used in another expression with an operator.

More context from MSDN.

It specifically mentions:

A declaration-statement declares a local variable or constant. Declaration statements are permitted in blocks, but are not permitted as embedded statements.

So it looks more like a 'language restriction' more than 'lack of a return value', although that (lack of return values of statements) must have influenced such a restriction.

Upvotes: 2

Related Questions