A C# component to access persistent data

Access persistent data in Grasshopper in C#

How to access the persistent data property of Grasshopper components in C#.

Say for example you want to read the value of ‘2’ which is saved internally within a ‘Num’ component.

grasshopper-persistent-data-access

We can look up the Num class and access the property from here quite easily. But what if we want to do it a bit more generically, so we can access the persistent data within any component?

We can do this by accessing the GH_PersistentParam(T) class. But because this class is in a different namespace/class hierarchy to the IGH_Param class (where we would normally be working to access component properties) it takes a little bit of work to manoeuvre data without Grasshopper having a small fit. (Read here for a forum post where David Rutten explains the class hierarchy behind Grasshopper.)

Two similar solutions I’ve produced today are:

var param2 = Component.Params.Input[0].Sources[0] as Grasshopper.Kernel.GH_PersistentParam<Grasshopper.Kernel.Types.GH_Number>;
A = param2.PersistentData[0];

…and the one-line alternative:

A = ((Grasshopper.Kernel.GH_PersistentParam<Grasshopper.Kernel.Types.GH_Number>) Component.Params.Input[0].Sources[0]).PersistentData[0];

This is a great simplification of the problem – it will only looks at the 1st component connected to the 1st input. And since PersistentData returns as GH_Structure, rather than dealing with data trees, it is easiest just to use square bracket notation to retrieve the first item (which is valid if we only have one item in our persistent data, as in this example).

3 thoughts on “Access persistent data in Grasshopper in C#”

  1. You could tidy up the two line example to remove the ‘as’ stuff to be simply:

    var param2 = ((Grasshopper.Kernel.GH_PersistentParam<Grasshopper.Kernel.Types.GH_Number>) Component.Params.Input[0].Sources[0]);
    A = param2.PersistentData[0];
    

    This (and the other work done today) is a great example of the power of inheritance, but also of the need for good SDK documentation from GH!

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: