Dynamic variable name in C#

bool myVar = 5;
Debug.Log(myVar);    // 5
string myVarName = "myVar";
// {turnStringToVarRef("myVar")} = 10
Debug.Log(myVar);    // 10

How do I get it to work? Is it possible?

I looked up literally the title “Dynamic variable name C#”, but it prompts me a certain property called “dynamic” (and questions related to it), which looking by the code seems to not have anything related to my question.

This is called reflection in C#. You use a string to look up a property of some kind at runtime.

https://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection-in-c-sharp

It’s a bit fiddly and tedious but it works. It is also not necessarily going to be very performant, but it might suit your needs anyway.

I believe with newer flavors of C# you can use the ‘dynamic’ keyword but I’m not 100% sure about that.

If you like you can also store things in a Dictionary indexed by a string.

I believe that should be possible using reflections, but i’ve never done something like that, and honestly, i dont know why i would. May i ask what you need this for? There most likely is some better solution for what you are doing.

Anyways, reflections reference: Attributes and reflection - C# | Microsoft Learn

Also, out of curiosity, from which language are you coming where working like that is a common convention?

Edit: Aaand @Kurt-Dekker beat me to it by a second or so :stuck_out_tongue:
Edit2: Also Kurt i dont think dynamic can be used for something like that. It’s simply a dynamically typed version of var as far as i know (using reflection internally tho), making C# both a statically and dynamically typed language, which is rather weird. But please correct me if i’m wrong.

2 Likes

Thanks for replying as well @Yoreki . You added good reference stuff there, and I also agree this is a rarely-needed feature for “general game programming.” There really is almost always a better way, unless you have some weird technical limitation you’re working with.

I’ll also add that my Datasacks module does this to retrieve Datasacks, getting them by string, once they’re all in a big Dictionary. But the common case is to use generated code for Datasacks.

Datasacks generates code for you so you can benefit from compiler checking, but still get dynamic access via string.

Datasacks is presently hosted at these locations:

https://bitbucket.org/kurtdekker/datasacks

That’s what arrays are for, using indexes for the name. i=0; A=5; i=1; A_=10;. Dynamic is the opposite of static. x=5; is always the same box, A*=5; could be any box, different each time. A practical example: currentGun=2; (set globally) then Guns[currentGun].fire().*_