Cast IList<IGH_Goo> to List<GH_Number>

I am trying to access a list of type GH_Number stored in a GH_Structure with tree.getBranch() method, like so:

List<GH_Number> buildingParams1 = (IList<IGH_Goo>)tree.get_Branch(new GH_Path(rndBl, rndPa, 0));

I get an invalid cast ('cannot implicitly convert type 'System.Collections.Generic.IList<Grasshopper.Kernel.Types.IGH_Goo> to ‘System.Collections.Generic.List<Grasshopper.Kernel.Types.GH_Number>’. An explicit conversion exists (are you missing a cast?)

What am I doing wrong?

Thanks! :slight_smile:

You’re casting your branch to IList<IGH_Goo>, which is not the type of your variable. Thus the code won’t compile.

Your cast needs to be to the same type, or an assignable type. In this case you’re even dealing with generics, which makes it harder still.

I think you’re best off doing an element by element cast.

var branch = tree.get_Branch(...);
var numbers = new List<GH_Number>();
foreach (var element in branch)
  numbers.Add(element as GH_Number);

Thank you ever so much David!
Works like a dream.