Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline assignment on IF statement

Tags:

c#

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;
}
like image 857
Chris Hammond Avatar asked Oct 27 '16 07:10

Chris Hammond


People also ask

Can we do assignment in if statement?

Can we put assignment operator in if condition? Yes you can put assignment operator (=) inside if conditional statement(C/C++) and its boolean type will be always evaluated to true since it will generate side effect to variables inside in it.

Can we use assignment operator in if condition in Python?

No. Assignment in Python is a statement, not an expression.

How do you do an inline if statement in Python?

Syntax of Inline if-else in Python To write an Inline if-else statement we have to follow this syntax. In this syntax, <expression1> will be returned or executed if the condition is true, or else <expression2> will be returned or executed, and these conditions are always executed from left to right.

What is inline assignment?

Inline Assignment Grading provides a way to grade assignments within your Blackboard course. Instead of needing to download student files for viewing, instructors are able to view these files “inline,” i.e. in the web browser, without the need for plug-ins or additional software.


1 Answers

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);
}
like image 194
Heinzi Avatar answered Sep 24 '22 05:09

Heinzi