Ankit
Ankit

Reputation: 6622

how to dynamical pass generic-type same as type of parameter?

I am trying to do something like this:

public static void ShowTaskPane(UserControl type)
        {            
                var item = set.OfType<typeof(type)>().FirstOrDefault();
     }

but this is not working, I want to select object of type or passed parameter. Method signature, if required, i can change it, but suggest me how to do it?

Upvotes: 0

Views: 88

Answers (1)

Habib
Habib

Reputation: 223217

You can define your method as:

public static void ShowTaskPane<T>()
{
    var item = set.OfType<T>().FirstOrDefault();
}

and then call it like:

ShowTaskPane<UserControl>();

Or if you method is suppose to return the control then:

public T ShowTaskPane<T>()
{
    return set.OfType<T>().FirstOrDefault();
}

call it like:

var item = ShowTaskPane<UserControl>();

For comment: is there anyway I can restrict th type of T to just the subtype of UserControl?

You can specify the constraint like:

public T ShowTaskPane<T>() where T : UserControl
{
    return set.OfType<T>().FirstOrDefault();
}

Upvotes: 1

Related Questions