Reputation: 7489
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
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
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
Reputation: 20194
Action<string> action = new Action<string>( str =>
{
if (str == null)
Console.WriteLine("isnull");
else
Console.WriteLine("isnotnull");
});
Upvotes: 2
Reputation: 15579
You would have to do it like this:
var action = new Action<string>(str => Console.WriteLine((str == null) ? "isnull" : "isnotnull"));
Upvotes: 5