Runtime Type instantiation question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ben Fidge

    #1

    Runtime Type instantiation question

    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(Bas eClassType 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(con st oClass : TFormClass) : TForm;
    end;

    ...

    function TFactory.Create Class(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.Create Instance(TForm) ;
    oForm2 := TFactory.Create Instance(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!


  • Jon Skeet

    #2
    Re: Runtime Type instantiation question

    Ben Fidge <ben.fidge@styl usnet.com> wrote:[color=blue]
    > In C# how would I create an instance of a given type at runtime without
    > knowing the exact class at designtime?[/color]

    Load the assembly containing the type you wish to instantiate, use
    assembly.GetTyp e to get the appropriate Type instance, then call
    Activator.Creat eInstance.

    --
    Jon Skeet - <skeet@pobox.co m>
    Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

    If replying to the group, please do not mail me too

    Comment

    Working...