DCSIMG
return a = “hello”; What will Happen? - IronShay

return a = “hello”; What will Happen?

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.

kick it on DotNetKicks.com Shout it
Published Wednesday, April 28, 2010 9:35 AM by shayf
תגים:,

Comments

# return a = ???hello???; What will Happen? - IronShay Blog

Pingback from  return a = ???hello???; What will Happen? - IronShay Blog

Wednesday, April 28, 2010 6:28 PM by return a = ???hello???; What will Happen? - IronShay Blog

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: