cristianqr
cristianqr

Reputation: 688

How to use Type.GetType in a expression lambda

I'm trying do the next instruction in c#:

Form form = this.MdiChildren.FirstOrDefault(x => x is Type.GetType("MyFormName"));

But i have a error: Method name expected.

What would be the correct usage of the instruction.

Upvotes: 3

Views: 721

Answers (1)

Servy
Servy

Reputation: 203834

Since you have a Type instance you need to use IsAssignableFrom instead of is:

x => Type.GetType("MyFormName").IsAssignableFrom(x.GetType())

This of course assumes that you really can't reference the actual type at compile time. If you can, then you could instead simplify this code to:

.OfType<MyFormName>().FirstOrDefault();

Which is going to have something internally that resembles:

x is MyFormName

Which is how the is operator is designed to be used.

Upvotes: 7

Related Questions