Sign in to follow this  

Variable variables in C#

This topic is 4398 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In for instance ActionScript (programs flash) there is a possibility of calling a variable by typing a part of its name, and add the rest of the name as the content of another variable. Ex:
var_1 = "Hello";
var_2 = 1;
var_3 = _root["var_" + var_2];

// var_3 gets the value from var_1, ie. "Hello"
Does anything like that exist in C#?

Share this post


Link to post
Share on other sites
Hm, there might be an easier way, as I don't know C# well, but you can use arrays in the situation you have there. Something like:

(c++)

//create array
array[0] = "hello";

int index = 0;

myVar = array[index];


This will accomplish the same thing as you posted, but will not be fun or organized to have several variables each in an array like that.

Share this post


Link to post
Share on other sites


Type t = theObject.GetType();
// field is a member variable
t.GetField("FieldName").GetValue(theObject));
// or get property, which is a property defined like
// int SomeProperty { get{ return 0; } }
t.GetProperty("PropertyName").GetValue(theObject, null));



Share this post


Link to post
Share on other sites
Does ActionScript have arrays, even? o_O

If you really need to be able to map from a "name" to some "value", then use - a map.


#include <map>
#include <string>
//...

std::map<std::string, std::string> vars;
vars["1"] = "Hello";
vars["2"] = "1"; // can't store an int. C++ is statically typed.
vars["3"] = vars[vars["2"]];

Share this post


Link to post
Share on other sites
Oops. (Don't know enough C# to help, and yeah, obviously I've been helping way too many people with C++ in a row... come on people, use a more friendly language :) )

Share this post


Link to post
Share on other sites
A possible way for this to work is definately an array, here is some sample code if you're still having trouble.

string[] var;
var = new string[];

var[1] = "Hello";
var[2] = "1";
var[3] = var[1] + var[2];

Yes using that code var[2] won't be and integer so if you were to add numbers in that array 1 + 2 = 12 so be careful about that. If you need more help just PM me or something.

Share this post


Link to post
Share on other sites
If you're planning to use different variables types (like your AS snippet suggests), I'd recommend using one of (specialized) collections types.
If you only need a fixed list of strings or integers, an array would be a lighter solution.

Share this post


Link to post
Share on other sites
You could define a new native types layer utilizing the map feature so that it works identical to actionscript.

For example you could declare a intX or floatX type and invoke GetVarX( "var_name") or however you define it. You'd of course need to make sure to overload all the arithmetic operators so that they don't lose any flexibility over the real native types.

Share this post


Link to post
Share on other sites
I think he's trying to get at variables that are just in a specific scope, not elements of some sort of dictionary or map. If that's the case, then he needs to use reflection. I posted code on how to do what he wants to do which will work to get at fields and properties of an object. I don't know how to just get at a variable that isn't part of an object:



using System.Reflection;
using System;

class dummy
{
public int field;
public int Property
{
get { return 10; };
}
}

void f()
{
int someInt = 10;
dummy c = new dummy();
Type dummyType = c.GetType();

int fieldValue = dummyType.GetField("fi" + "eld").GetValue(c);
int propertyValue = propertyType.GetProperty("Prop" + "erty").GetValue(c);

// now how do I get the value of "someInt" by name? It's not a
// property or field, so I can't do a "GetType" on anything.

Console.WriteLine("Value of field: {0}", fieldValue);
Console.WriteLine("Value of Property: {0}", propertyValue);
}




Share this post


Link to post
Share on other sites
Quote:
Original post by smr
I think he's trying to get at variables that are just in a specific scope, not elements of some sort of dictionary or map. If that's the case, then he needs to use reflection. I posted code on how to do what he wants to do which will work to get at fields and properties of an object. I don't know how to just get at a variable that isn't part of an object:

The simple answer is: You don't. You could, of course, build a preprocessor that would build an internal registry of variables that were added and removed from said registry as they came into scope and left scope, however such a process would be rather...stupid.

He could also build a varadic type with a centralized registry that on construction registered the variable and then he could fetch it from that registry (which is essencially what you would do with a dictionary), which is all _root really is (albeight with a bit more stuff in it).

Share this post


Link to post
Share on other sites
Quote:
Original post by Washu
He could also build a varadic type with a centralized registry that on construction registered the variable and then he could fetch it from that registry (which is essencially what you would do with a dictionary), which is all _root really is (albeight with a bit more stuff in it).


But wouldn't GetField and GetProperty accomplish the same thing? Since you have an actual object with a type, you can get at its fields with the GetX methods. Is there a concept in .NET like pythons "__locals__"?

Share this post


Link to post
Share on other sites
Quote:
Original post by _Danneman_
Does anything like that exist in C#?

Not exactly. But there are four ways to approximate this:

1.) Use the System.Reflection methods. For instance, to get the value of a field in a class, use the following.
using System;
using System.Reflection;
using System.Security;

public class Dummy
{
public string s = "stored string value";
public string X
{
get
{
return this.s;
}
set
{
this.s = value;
}
}
}

// Elsewhere in code
public static void Main()
{
// Use a try-catch block in real software to catch
// SecurityExceptions that might arise.
Dummy d1 = new Dummy();
Dummy d2 = new Dummy();
d2.X = "foo";

Type t = Type.GetType("Dummy");
FieldInfo fi = t.GetField("s"); // <-- equivalent variadic specification

// prints "stored string value"
Console.WriteLine("The value of the d1 field is: {0}", fi.GetValue(d1));
// prints "foo"
Console.WriteLine("The value of the d2 field is: {0}", fi.GetValue(d2));
}


2.) Use a GenericDictionary to store name-value pairs.

3.) Use an array, if the values are all the same type.

4.) Wait for C# 3.0. Then you can use (3) even if the values aren't all the same type, and the compiler will infer their type from the way in which the value is used.

Share this post


Link to post
Share on other sites
Quote:
Original post by smr
But wouldn't GetField and GetProperty accomplish the same thing? Since you have an actual object with a type, you can get at its fields with the GetX methods. Is there a concept in .NET like pythons "__locals__"?


No, because the instances wouldn't need to be class members. That particular solution is ugly though.

string name = "v";
int index = 1;
.
.
.
Var v1(name + index);
v = something;
.
.
.
Var var = Var.Get(name + index);


Disguised globals...silly idea.

Share this post


Link to post
Share on other sites

This topic is 4398 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this