I can define a delegate and write the query like this.
Func<string, bool> filter = s => s.Length == 5;
IEnumerable<string> query = names.Where(filter)
.Select(x => x.ToUpper());
My question is, if the Func<T, TResult>
is a delegate taking a string as argument and returning a bool, why cannot I say:
delegate bool D(string s);
D d = new D(delegate(string s) { return s.Length == 1; });
IEnumerable<string> query = names.Where(d).Select...
?
Because they are different types.
A shorter version giving the same kind of error:
delegate bool D(string s);
delegate bool F(string s);
D d = new D(delegate(string s) { return s.Length == 1; });
F f = d;
Error 1 Cannot implicitly convert type 'Program.D' to 'Program.F'
And the extension method Where
is defined as
Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
So you need a Func<string, bool>
and D
is similar but not compatible.
It's because two different delegate types (and Func<TSource, TResult>
is a delegate type, too) are considered different types, even if their signature is the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With