declare variables in argument list

It's possible in c# 7 to declare variables for out variables in argument list:

if (int.TryParse(input, out int result))
    WriteLine(result);

Is it possible to declare ("non out") variable in argument list? Like this:

if (!string.IsNullOrEmpty(string result=FuncGetStr()))
        WriteLine(result);
Jon Skeet
people
quotationmark

You can't do it in the argument list, no.

You could use pattern matching for this, but I wouldn't advise it:

if (FuncGetStr() is string result && !string.IsNullOrEmpty(result))

That keeps the declaration within the source code of the if, but the scope of result is still the enclosing block, so I think it would much simpler just to separate out:

// Mostly equivalent, and easier to read
string result = FuncGetStr();
if (!string.IsNullOrEmpty(result))
{
    ...
}

There are two differences I can think of:

  • result isn't definitely assigned after the if statement in the first version
  • string.IsNullOrEmpty isn't even called in the first version if FuncGetStr() returns null, as the is pattern won't match. You could therefore write it as:

    if (FuncGetStr() is string result && result != "")
    

To be utterly horrible, you could do it, with a helper method to let you use out parameters. Here's a complete example. Please note that I am not suggesting this as something to do.

// EVIL CODE: DO NOT USE
using System;

public class Test
{
    static void Main(string[] args)
    {
        if (!string.IsNullOrEmpty(Call(FuncGetStr, out string result)))
        {
            Console.WriteLine(result);
        }
    }

    static string FuncGetStr() => "foo";

    static T Call<T>(Func<T> func, out T x) => x = func();
}

people

See more on this question at Stackoverflow