Add new component on canvas based on Type (by casting)


I understand that to add component programmatically we can specify what component to add and then adding that to the document
Grasshopper.Kernel.Special.GH_Panel panel1 = new Grasshopper.Kernel.Special.GH_Panel();
this.onPingDocument().AddObject(panel1, false);

However, I would like to add dynamically by using the type extracted from:
Type type = obj.GetType();

Is there something like overload to generate new IGH_DocumentObject based on Type?
Because otherwise it means that I will need to create mapping for all the objects based on the type name?

Thank you.

This is done by reflection.

What is obj in this code?

Thank you so much for the tip! I managed to create a new IGH_DocumentObject by using the code below (reflection):

IGH_DocumentObject anObj = (IGH_DocumentObject) Activator.CreateInstance(compType);

Oops, sorry for not writing it clearly. Obj is IGH_DocumentObject instance

I’d recommend using Grasshopper.Instances.ComponentServer.EmitObject() to create a new instance based on the Component id of the object you already have.

Or even use Grasshopper.Instances.ActiveCanvas.InstantiateNewObject().

Ah, I see. In my case, that means I have to first generate the object first to get the ID and then only add it to canvas by using the method you gave.

Is there a difference if I use GHDocument.AddObject() as compared to Grasshopper.Instances.ActiveCanvas.InstantiateNewObject() ?

Thank you

Reflection is known for being „slower“. But unless you are planning to initiate a million components, this won‘t matter very much… It may also be possible that you are not initializing a component completely right. Initializing over the constructor might not be sufficient enough like in some software architectures. Although you could see this a bad design… Usually when you see the Factory pattern or similar this hints initializing over a constructor might not be enough. Don‘t know here though

I’m confused then. I thought you already had an IGH_DocumentObject in your obj variable. You only need the id in any case, which you can look up ahead of time.

I’m not entirely sure what problem you’re solving though.

Yes. The canvas method does much more. It ensures the object attributes are set up correctly. It handles initialisation codes. It adds undo data. Triggers redraws and solution updates…