7

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?

Trident D'Gao
  • 18,973
  • 19
  • 95
  • 159
  • 1
    This isn't just a C# syntax quality. It is sometimes handy in, say, if statements, allowing you to simultaneously assign and test. It does, however, make for more obfuscated code, so it doesn't see much use. Summary: assignment is an expression, not a statement! – Kenogu Labz Jul 19 '13 at 03:03
  • 5
    Another good one is lazy instantiation, as in `_myInstance ?? (_myInstance = new MyObject())` – McGarnagle Jul 19 '13 at 03:03
  • 5
    btn1.Visible = btn2.Visible = false; – EricLaw Jul 19 '13 at 03:08

2 Answers2

12

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.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • 2
    I very common use for them I have is any time I work with many of the IO classes to check the result of a read operation `while ((currentLine = streamReader.ReadLine()) != null) { ... }` – Scott Chamberlain Jul 19 '13 at 03:15
  • @ScottChamberlain Yep, that's a good example as well. – p.s.w.g Jul 19 '13 at 03:18
4

I generally use it for assigning the same properties to a control.

btnSubmit.Enabled = btnAdd.Enabled = btnCancel.Enabled = txtID.Enabled= false;
TheProvost
  • 1,832
  • 2
  • 16
  • 41