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

January 15. 2012 05:47 PM

clothing wholesalers

What an amazing post that I have ever come through. It gives the information that I was really searching for the past week and I am really satisfied with this post. Need more like this. Thank you.

clothing wholesalers

January 19. 2012 05:28 AM

beats by dre

What an amazing post that I have ever come through.

beats by dre

January 19. 2012 05:32 AM

beats by dre

I have ever come through.

beats by dre

January 20. 2012 11:33 AM

running shoes 2012


<a href='http://www.droseshoes.org'><strong>d rose shoes</strong></a> They compared this man to a dam animal! And yall sitting up here saying that's the best commercial I ever saw
<a href='http://www.2011hyperdunks.com'><strong>2011 hyperdunks</strong></a> ?! WTF they think of us as animals and we just accept it? Smh gET THAT monkey out of our beautiful Spainsh bull ring <a href='http://www.lebron9s.com'><strong>lebron 9s</strong></a>!! NO business to be there disrespect to our latin culture <a href='http://www.2011hyperfues.com'><strong>2011 hyperfuse</strong></a>! All tatted up n sh*t <a href='http://www.kobe7shoes.org'><strong>kobe 7 shoes</strong></a>!!

running shoes 2012

January 20. 2012 11:34 AM

running shoes 2012

[url=http://www.adidashardland.com]adidas shoes[/url] Bulls guard Derrick Rose has been named one of the 20 finalists for the 2012 U.S [url=http://www.jeremyscottadidas2011.com]jeremy scott adidas 2011[/url]. Olympic Men’s team. Rose was a member of the 2010 USA World Championship team [url=http://www.adirisemid.com]adi rise mid[/url] that claimed the gold medal in Istanbul, Turkey. [url=http://www.lebron8christmas.com]lebron 8 christmas[/url] As the starting point guard for the 2010 U.S. squad, Rose averaged 7.2 ppg, 3.2 apg, and 2.1 rpg in 23.1 mpg [url=http://www.griffinsshoes.org]griffins shoes[/url]. [url=http://www.adizero15.com]adizero 15[/url]

running shoes 2012

January 20. 2012 04:58 PM

astrologie

No man can reveal to you nothing but that which already lies half-asleep in the dawning of your knowledge.

astrologie

January 21. 2012 07:27 AM

Resume writing service

This posting is marvelous and what a fantastic research that you have done. It has helped me a lot. thank you very much. Feel free to visit my buy portfolio lighting site.

Resume writing service

January 25. 2012 07:56 AM

thesis writing service

Did you know about Freelance writing job service? I wanted to tell that your ideas connecting to this good post is supreme! Thank you very much for creating it!

thesis writing service

January 25. 2012 10:05 AM

2011 nike hyperdunk

<a href='http://www.derrickroseshoe.org'><strong>derrick rose shoe</strong></a> My tour through China was amazing. The fan <a href='http://www.2010hyperfuse.com'><strong>2010 hyperfuse</strong></a> support was incredible and I got to meet a lot of great people. I also got to play with some really talented players so that was fun as well <a href='http://www.derrickrosenewshoes.com'><strong>derrick rose new shoes</strong></a>. I always get treated so well that I can't wait to come back <a href='http://www.derekroseshoes.com'><strong>derek rose shoes</strong></a>! hey derrick just wanted to let u know i'm a big fan all the way from africa!u shud come visit soon!what are ur hobbies <a href='http://www.supraspurple.com'><strong>supras purple</strong></a> ?

2011 nike hyperdunk

February 2. 2012 11:18 PM

long-branch-movers

It is a very profitable post for me. I've enjoyed reading the post. It is very informative and useful post. I would like to visit the post once more its valuable content.

long-branch-movers

February 3. 2012 02:50 PM

paterson-movers

Hi, just wanted to say I attended this conference last year, and found it by far the best of about 8 conferences that I attended in the field. Full of professional insight based on testing by experts that knew what they were talking about. I would certain

paterson-movers

February 4. 2012 07:57 AM

west-paterson-movers

I am really impressed by this excellent stuff on ZBrush which is a digital sculpting and painting program that has revolutionized the industry. I've enjoyed reading the nice post

west-paterson-movers

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