ccalboni
ccalboni

Reputation: 12490

Declare and assign a variable in if statement condition, reuse in statement body

I can't really phrase the question's title. Anyway, say I have a statement like:

if(myObject.SomeMethod() != null)
{
    DoSomethingWith(myObject.SomeMethod());
}

I'd like to avoid a double call to SomeMethod(). Ideally, something à la pattern matching like:

if(myObject.SomeMethod() result != null)
{
    DoSomethingWith(result);
}

Is there something in the language that can help me with this? At the moment, my choice is to go with:

var result = myObject.SomeMethod();
if(result != null)
{
    DoSomethingWith(result);
}

I know there's nothing wrong in the method above, it's very canonical. Simply put, a lot of syntactic sugar has been added to the language lately, allowing us to condense our code a lot: I'm asking because I don't know if there's something preventing if(myObject.SomeMethod() result != null) to work.

Upvotes: 2

Views: 3163

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460058

Well, i'd suggest to use a variable as you did in your third code. However...

You can use pattern matching if you don't want to use a variable:

if(myObject.SomeMethod() is var result && result != null)
{
    DoSomethingWith(result);
}

But note that this doesn't prevent access to the variable result. You can even access it after the if. If you want that you need a new scope: { if... }.

Upvotes: 10

Related Questions