- Posted by Shay Friedman on April 28, 2010
I came across an interesting piece of code the other day, something I didn’t even know possible in C#.
Consider the next code (which doesn’t make lots of sense, but it gets the point across):
public string Test()
{
string a;
return a = "hello";
}
What do you think will happen? what will be returned from this method?
…
……
………….
………………
So?
…
……
………….
………………
The answer is that this method will return “hello”.
Why did it happen?
When thinking more about it, this behavior is expected. It becomes very clear when reading about the assignment (=) operator on MSDN:
| "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." |
To make things even simpler, think about the syntax of multiple assignments in one line – b = a = “hello”; – this is exactly the same. In the sample above I just return the value instead of assigning it to the variable b.
All the best,
Shay.