This question already has answers here:
Conditional operator and Comparison Delegate
(2 answers)
Conditional statement, generic delegate unnecessary cast
(4 answers)
Why doesn't the C# ternary operator work with delegates?
(2 answers)
How can I assign a Func<> conditionally between lambdas using the conditional ternary operator?
(4 answers)
Closed 4 years ago.
I have a choice between two statically defined converters, and I want to use a ternary expression to make the choice:
Func<Input, Output> converter = useConverter1
? MyConverter.Converter1
: MyConverter.Converter2;
The compiler will not accept this expression. It fails with a message saying "There is no implicit conversion between 'method group' and 'method group'".
The structure of MyConverteris
public static class MyConverter
{
public static Output Converter1(Input input)
{
....
}
public static Output Converter1(Input input)
{
....
}
}
Can I work around this without an if-else statement?
Related
This question already has answers here:
Operator '==' cannot be applied to operands of type 'string' and 'int' [closed]
(2 answers)
Closed 4 years ago.
if (Properties.Settings.Default.BG == 1)
{
}
I think there is something I need to write before (1) but I don't know
To represent a string, you need to surround the value with double quotes. Currently you're comparing it to an integer. Instead, do something like this:
if (Properties.Settings.Default.BG == "1")
{
}
Another way to do this would be to call the built-in ToString() method that belongs to all objects:
if (Properties.Settings.Default.BG == 1.ToString())
{
}
This question already has answers here:
Converting Nullable<bool> to bool
(6 answers)
Compiler Error for Nullable Bool
(5 answers)
cannot implicitly convert type 'bool?' to 'bool'. An explicit conversion exists (are you missing a cast?)
(9 answers)
Closed 5 years ago.
Why this code works:
if (list?.Any() == true)
but this code doesn't:
if (list?.Any())
saying Error CS0266 Cannot implicitly convert type 'bool?' to 'bool'
So why is it not a language feature making such an implicit conversion in the if statement?
An if statement will evaluate a Boolean expression.
bool someBoolean = true;
if (someBoolean)
{
// Do stuff.
}
Because if statements evaluate Boolean expressions, what you are attempting to do is an implicit conversion from Nullable<bool>. to bool.
bool someBoolean;
IEnumerable<int> someList = null;
// Cannot implicity convert type 'bool?' to 'bool'.
someBoolean = someList?.Any();
Nullable<T> does provide a GetValueOrDefault method that could be used to avoid the true or false comparison. But I would argue that your original code is cleaner.
if ((list?.Any()).GetValueOrDefault())
An alternative that could appeal to you is creating your own extension method.
public static bool AnyOrDefault<T>(this IEnumerable<T> source, bool defaultValue)
{
if (source == null)
return defaultValue;
return source.Any();
}
Usage
if (list.AnyOrDefault(false))
This question already has answers here:
C# Conditional Operator Not a Statement?
(9 answers)
Closed 6 years ago.
Why is this code not valid? Pretty sure it's legit in C /C++
Pseudocode:
String s = Console.ReadLine();
int x = 0;
Int32.TryParse(s, out x) ? Console.WriteLine("Foo") : Console.WriteLine("bar");
The ternary operator is used to return values and those values must be assigned.
If you want to invoke void methods in a ternary operator, you can use delegates like this:
String s = Console.ReadLine();
int x = 0;
(Int32.TryParse(s, out x) ? new Action(() => Console.WriteLine("Foo")) : () => Console.WriteLine("bar"))();
console.writeline return void.. The conditional operator (?:) returns one of two values depending on the value of a Boolean expression
MSDN
As discussed here, in C#, not every expression can be used as a statement.
This question already has an answer here:
implicit operator using interfaces
(1 answer)
Closed 9 years ago.
I have the following implicit conversion operator:
public static implicit operator InputArgument<T>(T value)
{
return new InputArgument<T>(value);
}
The following is code in an ASP.NET MVC controller:
This works:
InputArgument<string> input = "Something";
This works:
InputArgument<Controller> input = this;
This works:
InputArgument<IPrincipal> input = new InputArgument<IPrincipal>(User);
But this doesn't work:
InputArgument<IPrincipal> input = User;
The last example gives the error:
> Cannot implicitly convert type
> 'System.Security.Principal.IPrincipal' to
> 'Engine.InputArgument<System.Security.Principal.IPrincipal>'. An
> explicit conversion exists (are you missing a cast?)
What could be the reason that this implicit conversion does not work for IPrincipal?
User-defined conversions are specified as not working on interfaces. If they did work on interfaces like this then you could end up in a situation where Bar<IFoo> is converted to IFoo via a representation-changing user-defined conversion when the object actually implements IFoo, which would be surprising.
This question already has answers here:
Why can't c# use inline anonymous lambdas or delegates? [duplicate]
(4 answers)
Closed 9 years ago.
I'm trying to learn C#'s restrictions on an anonymous type. Consider the following code:
var myAwesomeObject = new {
fn1 = new Func<int>(() => { return 5; }),
fn2 = () => { return 5; }
};
So we've got two properties that are actually functions:
fn1: A Func<int> that returns 5.
fn2: A lambda function that returns 5.
The C# compiler is happy to work with fn1, but complains about fn2 :
cannot assign lambda expression to anonymous type property.
Can someone explain why one is ok but the other is not?
Because there is no way for the compiler to know the type of () => { return 5; }; it could be a Func<int>, but it could also be any other delegate with the same signature (it could also be an expression tree). That's why you have to specify the type explicitly.