Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "someString += AnotherString = someString;" valid in C#

Tags:

c#

.net-3.5

I was writing some code today and was mid line when I alt-tabbed away to a screen on my other monitor to check something. When I looked back, ReSharper had colored the 3rd line below grey with the note "Value assigned is not used in any execution path".

var ltlName = (Literal) e.Item.FindControl("ltlName");
string name = item.FirstName;
name += 

ltlName.Text = name;

I was confused; surely this code can't compile. But it does, and it runs too. The line "name +=" has no effect (that I could tell) on the string. What's going on here?

(Visual Studio 2008, .NET 3.5)

like image 471
Ed Schwehm Avatar asked Sep 02 '10 18:09

Ed Schwehm


2 Answers

Notice that newlines are not special in C#. Because of the following line, the complete statement to the compiler is

name += ltlName.Text = name;

which is a valid statement (it assigns name to ltlName.Text, then append it to name.)

like image 111
kennytm Avatar answered Sep 24 '22 14:09

kennytm


It's doing this:

name += ltlName.Text = name;

or to make it slightly clearer:

name += (ltlName.Text = name);

The result of the property setter is the value which was set, so it works a bit like this:

string tmp = name;
ltlName.Text = tmp;
name += tmp;

It's simpler to observe this when you've got different variables involved though, and just simple assignment as the final step rather than a compound assignment. Here's a complete example:

using System;

class Test
{
    public string Text { get; set; }

    static void Main()
    {
        Test t = new Test();

        string x = t.Text = "Hello";
        Console.WriteLine(x); // Prints Hello
    }
}

The simple assignment rules (section 7.17.1) are used to determine the result of the expression:

The result of a simple assignment expression is the value assigned to the left operand. The result has the same type as the left operand and is always classified as a value.

So the type of ltlName.Text = name is the same type as ltlName.Text, and the value is the one that's been assigned. The fact that it's a property rather than a field or local variable doesn't change this.

like image 22
Jon Skeet Avatar answered Sep 20 '22 14:09

Jon Skeet