tag:blogger.com,1999:blog-3339062625442125125.post661609349633426233..comments2023-06-18T12:19:43.363+01:00Comments on Andrea Angella, Software is my passion.: Scope of Local Variables in C# and C++Anonymoushttp://www.blogger.com/profile/16030164472457151873noreply@blogger.comBlogger2125tag:blogger.com,1999:blog-3339062625442125125.post-29518990104018799762012-11-19T14:06:02.950+00:002012-11-19T14:06:02.950+00:00C++ is consistent because simply allows everything...C++ is consistent because simply allows everything. It always assume you know what you are doing. It is by design :)<br /><br />What you say about shadowing a class field is true. C# is permissive in some situations.<br /><br />I tried to change a little bit your code with this:<br /><br /> class MyClass<br /> {<br /> int x = 10;<br /><br /> public void Load()<br /> {<br /> x = 10;<br /> int x = 0; <br /> }<br /><br /> public void Print()<br /> {<br /> Console.WriteLine(x);<br /> }<br /> }<br /><br />This code does not compile!!! :)<br /><br />You get the following error:<br /><br />Error 1 Cannot use local variable 'x' before it is declared. The declaration of the local variable hides the field 'ConsoleApplication.MyClass.x'. <br /><br />Anyway, ReSharper detects this and nobody stop you to set severity to "Error".<br /><br />This is one of the reason why some people like using underscores before the name of a field. However, I honestly don't like it. I use "this" only in constructors and generally I tend to avoid to use local variables with the same name of fields.<br /><br />Thanks for you comment. Very interestingAnonymoushttps://www.blogger.com/profile/16030164472457151873noreply@blogger.comtag:blogger.com,1999:blog-3339062625442125125.post-55212451231621537442012-11-19T12:51:29.806+00:002012-11-19T12:51:29.806+00:00C++ seems more logical and consistent given that C...C++ seems more logical and consistent given that C# does allow a method variable to shadow a class field but I think that the C# behaviour is preferable for avoiding mistakes. I've hit a few bugs where class fields were accidentally redeclared in methods so I would like the compiler to prevent that too.<br /><br />e.g. <br />class MyClass<br />{<br /> int m_X = 10;<br /> public void Load()<br /> {<br /> int m_X = 20; // mistake, shadowed this.m_X!<br /> }<br /> public void Print()<br /> {<br /> Console.WriteLine(m_X);<br /> }<br />}IanSnoreply@blogger.com