theSpyCry
theSpyCry

Reputation: 12283

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

?

Upvotes: 4

Views: 7069

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273264

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.

Upvotes: 3

Stefan Steinegger
Stefan Steinegger

Reputation: 64628

These are not the same type, even if they are compatible.

You need to "cast" it:

var query = names.Where(new Func<string, bool>(d))

I usually just do:

var query = names.Where(x => d(x))

Upvotes: 3

Botz3000
Botz3000

Reputation: 39610

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.

Upvotes: 3

Related Questions