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 MyFooClass's name or reference I want to receive it from outside. I'll instantiate them inside my adapter code.
For example:
public void FillWsvcStructs(DataSet ds, ClassType Baz)
{
IFoo.Request = ds.DataTable[0].Request;
IFoo.Modulebq = string.Empty;
IFoo.Clasific = string.Empty;
IFoo.Asignadoa = ds.DataTable[0].Referer;
IFoo.Solicita = "Jean Paul Goitier";
// Go with sub-Elems (Also "Interfaceated")
foreach (DataSet.DataTableRow ar in ds.DataTable[1])
{
if ((int) ar.StatusOT != (int)Props.StatusOT.NotOT)
{
///From HERE!
IElemRequest req = new (Baz)(); // I don't know how to do it here
///To HERE!
req.Id = string.Empty;
req.Type = string.Empty;
req.Num = string.Empty;
req.Message = string.Empty;
req.Trkorr = ar[1];
TRequest.Add(req);
}
}
}
You need a generic:
The generic constraint ("
where...
") enforces that the type you pass in implements theIElementRequest
interface and that it has a parameter-less constructor.Assuming you had a class
Baz
similar to this:You would invoke this method like so:
Addendum
Multiple, different, generic type parameters can each have there own type constraint:
That's probably best solved by using generics:
If you have multiple types that you need to be able to access/instantiate, the declaration follows the same rules (as may easily be gathered from msdn):
You probably want to use Activator.CreateInstance.
IElemRequest req = (IElemRequest) Activator.CreateInstance(Baz);
If the type that
Baz
represents has a constructor that takes parameters, the complexity of that will grow (as you'll have to use Reflection or dynamic calls to make it work). IfBaz
doesn't represent a type that inherits fromIElemRequest
, you will get an ugly runtime error.Generics and their constraints should do what you want, I believe:
The method:
Calling the method:
I think you want generics.
Declare your method like this:
The
new()
constraint requiresT
to have a public parameterless constructor, and theIElemRequest
constraint ensures it implementsIElemRequest
.