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)
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
.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With