11

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; } 
3
  • 1
    Heinzi answer is correct, but I don't advise you to do that. If you have multiple conditions your if will become unreadable. In the end what is you benefit from this ? Commented Oct 27, 2016 at 7:36
  • I have to process a data file and need to look for a list of expressions so there will be multiple expressions each on its own if () statement Commented Oct 27, 2016 at 7:38
  • You can do that properly with only one Match variable and multiple bool variables, but if you feel that this is looking better go on. Mark the answer of Heinzi as correct. Commented Oct 27, 2016 at 7:42

1 Answer 1

22

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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

And for those looking for null check specifically, it turns out that 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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.