Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# conditional operator - Call method if condition is true else do nothing

Tags:

c#

C# provides conditional operator (?:) that returns one of two values depending on the value of a Boolean expression. eg

condition ? first_expression : second_expression;

My question is can we use the same syntax to call a method when condition is true? and when condition is false then do nothing

 public void Work(int? val)
 {
   var list = new List<int>();

   //ofcourse line below doesn't work
   //but is it possible to call method when condition is true and else do  nothing

   val.HasValue? list.Add(val.value) : else do nothing
} 
like image 337
LP13 Avatar asked Aug 16 '26 10:08

LP13


1 Answers

the ?: has also been referred to as the ternary operator in the past. Ternary, for three. if this, then do this, else do this.

You have two expressions. If this, do this. This is exactly the point of an if statement. You are trying to fit your case into a construct that it isn't designed for. Don't do this.

Use the correct operation for the job:

if(val.HasValue)
{
    list.Add(val.value)
}
like image 174
Jonesopolis Avatar answered Aug 17 '26 23:08

Jonesopolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!