Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does assignment operator return the assigned value in C#? [duplicate]

Tags:

c#

The assignment operator in C# returns the assigned value. It's not clear where/how this feature can be helpful. Using it in a weird syntax like this can save you a line of code, but won't do any good to readbility:

   private String value;
   public void SetAndPrintValue(String value)
      PrintValue(this.value = value);
   }
   private static void PrintValue(String value) {
      /* blah */
   }

What is its purpose then?

like image 525
Trident D'Gao Avatar asked Jul 19 '13 03:07

Trident D'Gao


1 Answers

Chained assignment is a staple of many languages going back to C (and probably earlier). C# supports it because it's a common feature of such languages and has some limited use—like the goto statement.

Occasionally you might see code like this:

int a, b, c;
for(a = b = c = 100; a <= b; c--)
{
    // some weird for-loop here
}

Or this:

var node = leaf;
while(null != node = node.parent) 
    node.DoStuff();

This might make some code a little more compact, or allow you to do some clever tricks, but it certainly doesn't make it more readable. I'd recommend against it in most cases.

like image 52
p.s.w.g Avatar answered Oct 20 '22 07:10

p.s.w.g