How to create global variables in custom C# components?

I was wondering if there is a similar function to the python scriptcontext.sticky in c#?

I am creating a socket, and connecting to a server, then want to pass/share the handle to that active socket (the socket object) between different c# components which will be doing the reading/writing. I was able to do this in python, by making the socket a sticky variable, but cant seem to do the same in C#. Below is a short snippet of the connection, I want to make clientSocket object global, or sticky.

// Global Variable

    Socket clientSocket; 

    public bool startClient(string serverIP, int serverPort)
        clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        System.Net.IPAddress ip = System.Net.IPAddress.Parse(serverIP);
        IPEndPoint clientEndPoint = new IPEndPoint(ip, serverPort);


Any ideas on how to achieve this?

Edit: I have been doing some research on this and it seems like the solution lies in making it a class-level variable. However, I am still not sure on the details on how to do that.


One C# script cannot access any of the fields of any other C# script. There is no global space to put data. If the data is serializable, you can of course choose to put it anywhere (in a file, in the registry, in the clipboard, in a loose text panel on the canvas, …). But Grasshopper was designed with the idea that any data shared between various components has to be shared via wires. Doing it in another way will require a fair amount of hacking and will be easier to accomplish using a Visual Studio solution where you can create a shared space for data.

Very informative, thanks again David. Your serialization suggestion seemed to do the trick. Now I have my client component writing to a common database that other components can access.

But how does scriptcontext.sticky do it?
I find it useful but it’s only in GhPython.

I have used a static class to keep global data, but you need to keep track of document transactions Like new, close ect

Could you maybe share a snippet how that’s done?

Just google C# Singleton pattern. However this won‘t work from a script component because the Script class itself varies and for accessing it you need to know the actual scriptinstance, which changes each time your script gets recompiled. On Pluginlevel this is a great way.