IronShay

Ironing code, geek t-shirts and even presentations!

NAVIGATION - SEARCH

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


Comments (10) -

the more practical example would be this:

MyObject instance;
if ((instance = TryGetMeMyObject()) != null)
{
}

Reply

Croatia Dalibor Carapic

Erm ... I don't get it, what did you expect that it would return? What other option is there?

Donatas:
Why is your example more practical?

Reply

@Donatas: right, it's probably more realistic. but I don't like this syntax too much, a bit confusing and makes maintenance harder.

@Dalibor: actually I thought that the compiler would throw an error... I knew this syntax existed on C++ but I'd never actually run into it in C# (until a few days ago).

Reply

Austria Martin Ennemoser

If you think of the assignment as a method call it becomes more obvious that the assignment happens before the return:

return a.Assign( "hello" );

Reply

I know in C++ if you do

if (a = "hello")

it will return true, because the assignment was successful.  I kind of expected the same thing from C# code.  I've never tried returning a = "hello" in C++ though.  I wonder if it returns true or the value of a in that language.

Reply

I failed to see the point.  Isn't that part of the operator precedence?  Since 'return' is an operator, the assignment will be evaluated before the return gets evaluated since the assignment operator has higher precedence then return.

What am I missing here?

Reply

Eh... No shit Sherlock!

Reply

I've used this trick on properties before, to always guarantee that a member variable, when accessed is initialized

private IList<SomeObject> _someList;
public IList<SomeObject> SomeObjects
{
    get { return _someList ?? _someList = new List<SomeObject>(); }
}

Reply

Here's another practical example:

using (StreamReader reader = new StreamReader("file.txt"))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        list.Add(line);          // Add to list.
        Console.WriteLine(line); // Write to console.
    }
}

Reply

@Billkamm

>> if (a = "hello") will return true, because the assignment was
>> successful.

um.. no..  '(a="hello")' actually evaluates to a pointer to the string "Hello".  That pointer is then silently checked to see if it is not null, and that comparison would be determined to be true.

However, if you wrote 'if(a = null)' that would evaluate to false (since the expression is not "not null").  Since it is easy to write that by mistake when you meant "if (a == null)", many developers wrote that expression as "if (null == a)" which will generate a syntax error if you forget an equals sign.

Reply

Pingbacks and trackbacks (1)+

Add comment