Question: Can we restrict the scope of internally declared our parameters? #1813
-
I'm reading this article and it says
However I was wondering if it is not preferable to retain greater scope restrictions. I'd like to a fragment like this:
to generate a compiler error for the last line, by making the declared "something" out of scope outside of the "if" block. Why was this not done? If I want it to not be out of scope then I'd simply declare it before the "if" block. |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments
-
It was decided that by not having leaky scope severely limited the use cases in which the feature could be used. Big debate ensued. The language designers made their decision and that's what was implemented. |
Beta Was this translation helpful? Give feedback.
-
Jon Skeet said that it would be really annoying if you couldn't do something like this: public void DoSomethingWithFoo()
{
// return because the whole method depends on foo
if (!TryGetSomething(someKey, out var foo)) return;
// do something with foo
} And I totally agree. If the entire method depends on a conditonal (or even multiple ones, which tends to be the case when make Windows Forms) I prefer to check the opposite conditional and then return to save on indentation and lines. public void DoBar()
{
if (bar != null)
{
// Do bar stuff
}
} Isn't as clean as: public void DoBar()
{
if (bar == null) return;
// Do bar stuff
} In my opinion, so it would be annoying if I couldn't use out parameters in a similar fashion. |
Beta Was this translation helpful? Give feedback.
-
@AustinBryan - Jon's concerns are very reasonable, but I would have argued that the price is worth paying because one can always declare the variable in the old way and get what they want.
All that's been achieved is a small simplification in how we declare |
Beta Was this translation helpful? Give feedback.
-
@Korporal
That argument was made. It wasn't found compelling. You'll find a number of people on this repo who agree with your assessment and argued against this decision at the time. But at this point it's too late. The language has shipped with the "leaky" scope and to alter that would be a breaking change. |
Beta Was this translation helpful? Give feedback.
-
@Korporal
That was the exact position that was put forth and debated in-depth. At the end, the LDM (myself included) felt the price was not worth paying and we went with the direction you see now. It was made conscientiously and will full awareness of the concerns here. |
Beta Was this translation helpful? Give feedback.
It was decided that by not having leaky scope severely limited the use cases in which the feature could be used. Big debate ensued. The language designers made their decision and that's what was implemented.