This for C#? Passing Class type as a parameter
I have a class adapter that implements an Interface. I want to fill an array structure with MyFooClass instances where M
You need a generic:
public void FillWsvcStructs(DataSet ds) where TBaz : IElementRequest, new()
{
// ...
IElementRequest req = new TBaz();
// ...
}
The generic constraint ("where...
") enforces that the type you pass in implements the IElementRequest
interface and that it has a parameter-less constructor.
Assuming you had a class Baz
similar to this:
public class Baz : IElementRequest
{
public Baz()
{
}
}
You would invoke this method like so:
DataSet ds = new DataSet();
FillWsvcStructs(ds);
Multiple, different, generic type parameters can each have there own type constraint:
public void FillWsvcStructs(DataSet ds)
where TFoo : IFoo, new()
where TBar : IBar, new()
where TBaz : IElementRequest, new()
{
// ...
IFoo foo = new TFoo();
IBar bar = new TBar();
IElementRequest req = new TBaz();
// ...
}