-1

This is a simple snippet

public static void Foo(string s)
{
    int a = 0;
    int b = s.Length - 1;          
}

The intellisense of Visual Studio draws green wave line under a, shows it is assigned but never used. But it doesn't do this to b. Why? I haven't use b either until now, have I?

Claude Tan
  • 389
  • 1
  • 10
  • Though, if you do this `int a = s.Length; int b = s.Length - 1;`, then `a` isn't underlined anymore. I'd like to understand too. It's trivial, but would be nice to know. – blaze_125 Sep 07 '17 at 14:02
  • Yep, that duplicate @blaze_125 found has the answer, and better than mine below. – Jon Hanna Sep 07 '17 at 14:15

1 Answers1

1

That a is not used is an instance of warning CS0219.

a being assigned a constant value is utterly pointless, so at best you should delete it but also at worse (and hence the reason why the warning is useful) you did have some good reason for assigning a value to a but made some sort of mistake and so there is a warning and a green line (or a red line if you have warnings-as-errors turned on).

b is also not used, but it is more likely serving a purpose. Consider that the following is not a valid C# statement:

s.Length - 1;

Or even:

s.Length;

Mostly it's still not very useful to assign the value of a property to a variable and not use it, but we do occasionally need to call a property for a side-effect (a bad sign a lot of the time, all the same, for other reasons, but still) or so we can examine the result when debugging.

So that is not a warning case as it is more likely to be there for some good reason. (It will still be grey if you have the versions of Visual Studio that turns unused variables grey, I can't remember if they all do that or not).

Jon Hanna
  • 110,372
  • 10
  • 146
  • 251