Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this mean? int i = (i = 20);

Tags:

c#

I stumbled across this while starting to learn about vars here:

http://msdn.microsoft.com/en-us/library/bb384061.aspx

However, I have no idea how that is a legal expression (it is). I thought you couldn't assign to something using an a = (b=c) because (b=c) does not produce a value to assign?

Thanks for any clarification on the matter.

like image 784
3Pi Avatar asked May 16 '12 00:05

3Pi


People also ask

What does a<< b mean?

a<<b for integers means "shift left". The bitwise representation of a is shifted left b bits. This is the same as multiplying by (2 to the power of b ).

What does i ++ mean in C#?

For example, in the statement "v=i++", where the operator is in the postfix form, the value of "i" is assigned to "v" before the increment operation. In the statement "v =++i", where the operator is in the prefix form, the value of "i" is incremented first before being assigned to "v".

Can you use int i for loop?

When int i is declared outside the for loop, it can be accessed outside the for loop and inside but when you define it inside the loop, it can only be used inside the loop. Usualy, if you need it for the for loop define it inside the loop.


1 Answers

It is legal. From the = operator C# reference page:

The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result.

(emphasis mine)

The code in the example is contrived (and pointless), but it can be used in other cases to do useful things in a more concise way. For example:

BinaryTree tree; TreeNode node; if((node = tree.FindNodeForKey(10)) != null) {     // do useful things with returned node } 
like image 161
Sean U Avatar answered Sep 19 '22 04:09

Sean U