Chris Hammond Chris Hammond - 1 month ago 15
C# Question

Inline assignment on IF statement

Is it possible to "short-circuit" assignment and validation into an IF statement..

Something line this..

if ((Match m = Regex.Match(data, pattern)).Success)
{
Console.WriteLine(m.Groups["myField"].Value;
}

Answer

Assignment yes, declaration no:

Match m;
if ((m = Regex.Match(data, pattern)).Success)
{
    Console.WriteLine(m.Groups["myField"].Value);
}

Declaration expressions in C# have been suggested but have not been implemented yet.

Comments