theSpyCry
theSpyCry

Reputation: 12283

How to Load type from string directly into linq expression in C#?

This is the definition:

public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source);

How to replace TResult with something like:

Type.GetType("MyClass from assembly");

Upvotes: 0

Views: 366

Answers (2)

Lee
Lee

Reputation: 144136

You can't do this at compile time if you don't know the type involved, but you could write your own extension method for IEnumerable:

public static IEnumerable OfType(this IEnumerable source, Type t)
{
    foreach(object o in source)
    {
        if(t.IsAssignableFrom(o.GetType()))
            yield return o;
    }
}

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

You can't. Generic arguments enforce type security at compile time while the Type.GetType uses reflection and is not known at compile time. What exactly are you trying to achieve?

Upvotes: 4

Related Questions