This project is read-only.

Variable declarations within if statements

Topics: C# Language Design
Aug 17, 2014 at 7:39 AM
Edited Aug 17, 2014 at 8:10 AM
A common "if" construct:
Foo foo = a.Foo;
if (foo != null)
{
    Bar bar = foo.Bar;
    if (bar != null)
    {
        // use foo and bar
     }
}
Proposal: allow variable declarations in if-statements and while statements. Thus:
if ( (Foo foo = a.Foo) != null && (Bar bar = foo.Bar) != null)
{
   // use foo and bar
}
or equivalently using "var":
if ( (var foo = a.Foo) != null && (var bar = foo.Bar) != null)
{
   // use foo and bar
}
If only bar is needed, the proposed C# 6 null propagating operator ?. can help make this more readable even without this feature:
Bar bar = a.Foo?.Bar;
if (bar != null)
{
   // use bar
}
However used in conjunction with the present proposal we have:
if ( (Bar bar = a.Foo?.Bar) != null)
{
   // use bar
}
The proposed feature thus works well with the null propagating operator and should not be thought of as a competitor to it.

The scope of the declared variables includes the "else" clause. If a variable is not set (as is the case with bar in the first example when foo is null) it is set to the default value of its type.

I have limited this feature proposal to if and while statements only because I'm not expert enough to propose something broader. Presumably however other statements such as assignments also need to be considered, e.g.
var predicate = ( (Foo foo = a.Foo) != null && (Bar bar = foo.Bar) != null);
Aug 17, 2014 at 10:49 AM
I think this feature is already implemented. It's called "Declaration expressions". See here: https://roslyn.codeplex.com/wikipage?title=Language%20Feature%20Status&referringTitle=Documentation
Aug 17, 2014 at 11:37 AM
Well, that's nice! Sysadmins - feel free to delete this discussion since the feature is already implemented.