How to use Type.GetType in lambda expression

I am trying to execute the following statement in C #:

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

But I have a mistake: The expected method name.

What will be the proper use of the instructions.

+3
source share
1 answer

Since you have an instance Type, you need to use IsAssignableFrominstead is:

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

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

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

That will have something internally that resembles:

x is MyFormName

How the operator works is.

+7
source

All Articles