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)
It’s doing this:
or to make it slightly clearer:
The result of the property setter is the value which was set, so it works a bit like this:
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:
The simple assignment rules (section 7.17.1) are used to determine the result of the expression:
So the type of
ltlName.Text = nameis the same type asltlName.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.