Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate in a where clause

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...

?

like image 313
theSpyCry Avatar asked Jan 16 '23 21:01

theSpyCry


2 Answers

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.

like image 100
Henk Holterman Avatar answered Jan 29 '23 13:01

Henk Holterman


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.

like image 30
Botz3000 Avatar answered Jan 29 '23 13:01

Botz3000