Runtime Type instantiation question

  • Thread starter Thread starter Ben Fidge
  • Start date Start date
B

Ben Fidge

In C# how would I create an instance of a given type at runtime without
knowing the exact class at designtime?

For example, if I had a factory class that instantiated objects derived from
a common base class, how could I pass the "type" of class I want as a
parameter to the creation method and have it create and return an instance
of that "type"?

eg (in pigeon/pseudo C#!)

public class Factory {
public BaseClass CreateClass(BaseClassType oType) {
// create and return instance of BaseClassType
}
}


In Delphi, you can define a metaclass using "class of"

type
TFormClass = class of TForm;


and use this in your factory class as

TFactory = class
public
function CreateClass(const oClass : TFormClass) : TForm;
end;

...

function TFactory.CreateClass(const oClass : TFormClass) : TForm;
begin
Result := oClass.Create;
end;

which would take as a parameter the metaclass type of any class derived from
TForm

eg:

var
oForm : TForm;
oForm2 : TForm;

begin
oForm := TFactory.CreateInstance(TForm);
oForm2 := TFactory.CreateInstance(TForm2);
end;


Any help would be gratefully received,


Ben Fidge

Ps. Please don't bank on the Delphi examples being 100% as I've not touch it
for a while now!
 
Ben Fidge said:
In C# how would I create an instance of a given type at runtime without
knowing the exact class at designtime?

Load the assembly containing the type you wish to instantiate, use
assembly.GetType to get the appropriate Type instance, then call
Activator.CreateInstance.
 
Back
Top