Mladen Prajdić Blog

Blog about stuff and things and stuff. Mostly about SQL server and .Net

Weird C# compile possibility

Now this is something i really didn't think it would compile in C#.

 

private int _someVar = 0;
private void DoStuff1()
{            
    int _someVar = 0;
    _someVar = 6;
    // ... code that uses _someVar
}

private void DoStuff2() { _someVar = 5; // … code that uses _someVar }

 

We should at least get a warning if you ask me... 

One learns something new every day.

Legacy Comments


Jon
2007-05-23
re: Weird C# compile possibility
I dont get why you would think that would not work as you have declared the same variable for the class / form?
Its scope is valid across all methods of the class. The inner _someVar..within the actual function is local to the actual function, it takes precedence over the class variable _someVar.


Mladen
2007-05-24
re: Weird C# compile possibility
i didn't say that it wouldn't work.
i know it works.
i just think that this kind of "typo" in variable naming should at least give a warning.

Miha Markic
2007-05-24
re: Weird C# compile possibility
I don't think a warning should appear there because this is perfectly legal and a warning would only clutter output.

Mladen
2007-05-24
re: Weird C# compile possibility
well i'm of the opnion that the IDE and the compiler should make our life simpler.
and that they should report ambigouous code.

i understand that this is completly legal code, but i've been debugging this scenario yesterday for 2 hours, and a nice little warning would be nice.

i disagree about cluttering output.

Miha Markic
2007-05-24
re: Weird C# compile possibility
Yeah, well, warnings should be warnings - compiler can't guess whether you are right or wrong dealing with those variables or fields. So, if you are doing something as you want you might get a ton of useles warnings which would clutter the output and one would miss the real warnings.
Perhaps IDE could have an option to color local variables differently then fields.

Mladen
2007-05-24
re: Weird C# compile possibility
that's not a bad idea at all, Miha.

Jon
2007-05-24
re: Weird C# compile possibility
That would be a nice feature, local vs public to the class variables.

Jon
2007-05-24
re: Weird C# compile possibility
O one last thing, tell whoever wrote this to not start local variables with the underscore key. The hell kind of coding style is that!

Mladen
2007-05-24
re: Weird C# compile possibility
it was a copy/paste accident :)

Jesse
2007-05-29
re: Weird C# compile possibility
Some orgs I have worked in have a policy of always prefacing fields with "this" to make clear they are fields and not locals. doen't work for statics obviously.

I like the colorizing thing better though.

Richard
2007-06-09
re: Weird C# compile possibility
ReSharper provides a warning saying something like "Local variable hides instance variable" in this scenario.