The ternary operator inside Action <T> does not work

Have an Action delegate and try using the ternary operator with lambdas inside it:

Action<string> action = new Action<string>( str => (str == null) ? 
               Console.WriteLine("isnull") : Console.WriteLine("isnotnull")

Gives the old error "only assignment, reduction, etc. allowed."

Is it possible somehow?

+3
source share
4 answers

You would need to do this as follows:

var action = new Action<string>(str => Console.WriteLine((str == null) ? "isnull" : "isnotnull"));
+5
source
Action<string> action = new Action<string>( str => 
                    { 
                        if (str == null)
                           Console.WriteLine("isnull");
                        else
                           Console.WriteLine("isnotnull");
                    });
+2
source

, - . , . , Console.WriteLine, :)

+1

, , - . Console.WriteLine void , . , Console.WriteLine:

Console.WriteLine(str == null ? "isnull" : "isnotnull")

You can use this expression in your lambda.

0
source

All Articles