Runtime Type instantiation question

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!
 
J

Jon Skeet

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top