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

April 29. 2010 10:45 AM

Donatas

the more practical example would be this:

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

Donatas

April 29. 2010 11:06 AM

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?

Dalibor Carapic

April 29. 2010 11:16 AM

Shay Friedman

@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).

Shay Friedman

April 29. 2010 04:06 PM

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" );

Martin Ennemoser

April 29. 2010 05:14 PM

Billkamm

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.

Billkamm

April 29. 2010 09:09 PM

mchiao

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?

mchiao

April 29. 2010 09:48 PM

Ray

Eh... No shit Sherlock!

Ray

April 30. 2010 01:30 AM

Jon Erickson

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>(); }
}

Jon Erickson

May 11. 2010 08:40 PM

Chinh Do

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.
    }
}

Chinh Do

May 26. 2010 10:18 PM

James Curan

@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.

James Curan

April 12. 2012 10:08 AM

pingback

Pingback from yourmalefriend.yoursexualaids.net

Martin ennemoser | Yourmalefriend

yourmalefriend.yoursexualaids.net

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Subscribe Subscribe

That's Me!

Hi! I'm Shay Friedman
I'm Shay Friedman - a Visual C#/IronRuby MVP, a consultant and instructor of .NET technologies, author, speaker and new technologies freak
More about me

Contact Me

> Contact page
> Twitter: @ironshay
> LinkedIn profile

Search

Hosted By

I'm hosting this site on Arvixe and I'm very happy with it.
If you're looking for ASP.NET hosting, I highly recommend it
(and if you order from this link I also get some beer money!)
Web Hosting