Sean Thoman
Sean Thoman

Reputation: 7489

Ternary operator inside Action<T> not working

Have an Action delegate and trying to use the ternary operator inside of it with lambdas:

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

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

Is this possible somehow?

Upvotes: 3

Views: 520

Answers (4)

Martin Liversage
Martin Liversage

Reputation: 106816

The problem is not the lambda but the fact that the second and third expression in the ternary operator has to return something. Console.WriteLine has void return type and cannot be used as you are trying to. The solution is to put the ternary operator inside the call to Console.WriteLine:

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

You can use this expression in your lambda.

Upvotes: 0

Rex Morgan
Rex Morgan

Reputation: 3029

I believe the ternary operator has to return something. In your case it's not returning anything, just executing a statement. As Reddog said, you have to put your ternary inside the Console.WriteLine call, which is actually less code :)

Upvotes: 1

Diego
Diego

Reputation: 20194

Action<string> action = new Action<string>( str => 
                    { 
                        if (str == null)
                           Console.WriteLine("isnull");
                        else
                           Console.WriteLine("isnotnull");
                    });

Upvotes: 2

Reddog
Reddog

Reputation: 15579

You would have to do it like this:

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

Upvotes: 5

Related Questions