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; } In general: assignment yes, declaration no:
Match m; if ((m = Regex.Match(data, pattern)).Success) { Console.WriteLine(m.Groups["myField"].Value); } Declaration expressions have been suggested but have not been implemented yet.
However, depending on your C# version, there are workarounds for your particular use case.
C# 7: Since C# 7, arguments to out parameters in a method call can be declared inline:
string s = "123"; if (int.TryParse(s, out int i)) Console.WriteLine($"{s} has been parsed as {i}."); else Console.WriteLine($"Unable to parse {s}."); so you could work around your problem by designing a custom RegexTryMatch method:
public static bool RegexTryMatch(string input, string pattern, out Match match) { match = regex.Match(input, pattern); return match.Success; } an use this pattern when calling it:
if (RegexTryMatch(data, pattern, out Match m)) { Console.WriteLine(m.Groups["myField"].Value); } Adding such a method to the .NET class library is currently being discussed.
C# 9: The pattern matching features of C# 9 allow for a solution which is very similar to what you proposed:
if (Regex.Match(data, pattern) is { Success: true } m) { Console.WriteLine(m.Groups["myField"].Value); } or, alternatively:
if (Regex.Match(data, pattern) is {} m && m.Success) { Console.WriteLine(m.Groups["myField"].Value); } if (GetObjectThatMayBeNull() is {} obj) {...} is enough to both assign and check obj is not null! Note that like obj is not null, this bypasses user-defined equality (so if this matters you may want to add && obj != null - I think I'll do that on Unity)
if ()statement