8

is it possible in C# to use a String like a variable name ?
I have got a:

String x = "matrix1_2";
Microsoft.VisualBasic.PowerPacks.RectangleShape y = ???;


??? - there should be the name of variable...matrix1_2

hradecek
  • 2,455
  • 2
  • 21
  • 30

8 Answers8

14

No, you can't, and it makes no sense honestly to have a feature like that.

If you need to dynamically assign some data with key and value, you could use an dictionary:

Dictionary<string, RectangleShape> shapes = new Dictionary<string, RectangleShape>();
shapes.Add("matrix1_2", new RectangleShape( ... ));

Then you can simply read the "variable" like

shapes["matrix1_2"]
Denis Biondic
  • 7,943
  • 5
  • 48
  • 79
2

This is not possible.

You can't have dynamic variable names in C#, VB.NET or any .NET language. There is no support for such a feature.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 1
    Roslyn supports variable access like this, but other than that, this is correct. – McKay Feb 07 '12 at 20:06
  • @McKay - Roslyn is a very different matter. It is **not** C#. – Oded Feb 07 '12 at 20:07
  • @Oded, it's certainly not the best way to do it I don't think but if he knows what assembly the variable resides in he ought to be able to use reflection, right? – Brandon Moore Feb 07 '12 at 20:08
  • @BrandonMoore - reflection is not the same as declaring a variable name in runtime. – Oded Feb 07 '12 at 20:08
  • @Oded Roslyn is a different matter, but it is available in C# (CTP) – McKay Feb 07 '12 at 20:08
  • 1
    @Oded I didn't think he wanted to declare variable at runtime, but just access them by name at runtime. Maybe I'm misunderstanding the question though... – Brandon Moore Feb 07 '12 at 20:11
  • @Oded Right, that would solve his problem were it possible. It looks like what is actually has right now though is a variable that holds variable names... so maybe reflection is a possibility though it would require a workaround to account for the fact that reflection doesn't access method variables (as StriplingWarrior just pointed out on my answer). – Brandon Moore Feb 07 '12 at 20:17
  • 1
    @BrandonMoore - He probably just needs a collection but doesn't know how to express that. – Oded Feb 07 '12 at 20:18
2

No it is not. If "matrix1_2" is a local variable, then you can't do it as the variable might not even exist after the compiler is through, if it is actually an instance field, then reflection may help:

object value = obj.GetType().GetField(fieldName).GetValue(obj);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

You can get a field value from a dynamic type in this manner (using C# in a Silverlight 5 project).

Type itemType = item.GetType();
try
{
    PropertyInfo field = itemType.GetProperty(fieldName);
    object val = field.GetValue(item, null);
}
catch (Exception ex)
{
    // field doesn't exist, do something else
}

*Where "item" is a dynamic type generated at runtime (but doesn't have to be) and "fieldName" is a string for the property name you are looking for.

elliott.io
  • 31
  • 2
0

Seems like a bad idea. Try with enums or own datatypes /classes

chrs
  • 5,906
  • 10
  • 43
  • 74
0

You could with reflection, but I suspect in this case theere is a better design you could implement that would be better than using reflection. If you provide a little more info probably one of us could help you with that.

Declare a dictionary variable:

Dictionary<string, RectangleShape> rectangleDictionary = new Dictionary<string, RectangleShape>();

Then, where you would normallay write "matrix1_2 = somevalue;", instead write:

rectangleDictionary.add("matrix1_2", somevalue)

Then you'll be able to work with the variable name:

rectangleDictionary["matrix1_2"] = someothervalue;
rectangleDictionary["matrix1_2"].someproperty = something;

Microsoft.VisualBasic.PowerPacks.RectangleShape y = rectangleDictionary["matrix1_2"]; 
Brandon Moore
  • 8,590
  • 15
  • 65
  • 120
  • Probably there is a way to do what you want by using a Dictionary<> object to store the keys and values in. – Brandon Moore Feb 07 '12 at 20:08
  • Reflection does not allow access to variables within a method: only methods, fields, types, and properties. – StriplingWarrior Feb 07 '12 at 20:08
  • @StriplingWarrior That certainly does complicate the matter, though that could probably be worked around... definitely not worth working around though as I'm sure there are better options for his problem. – Brandon Moore Feb 07 '12 at 20:19
0

Does "matrix1_2" exist already? In other words, when you say y = ??? are you trying to access an existing variable or create one.

To my knowledge, there is no way to create a new "named" instance at run-time. However, you can retrieve the names of existing fields and select them using System.Reflection.

String x = "matrix1_2";
Microsoft.VisualBasic.PowerPacks.RectangleShape y;
Type type = typeof(MyType); // Get type pointer
FieldInfo[] fields = type.GetFields();
foreach (var field in fields)
{
        if (field.Name == "matrix1_2")
        {
            y = field;
        }
}

MyType above is the name of whatever class matrix1_2 lives in.

Justin
  • 8,853
  • 4
  • 42
  • 42
  • What if matrix1_2 isn't in a class, it's just a variable in the method? – McKay Feb 07 '12 at 20:47
  • @McKay - I do not believe that variable names are preserved inside a method. Once you compile down to CIL bytecode they are referenced by position (eg. V_0, V_1, V_2, etc) and whatever name you gave them is lost. So, even if you were able to dynamically create a new local variable, it would take some deep magic to refer to it in your C# programs. You might be able to use [AOP](http://en.wikipedia.org/wiki/Aspect-oriented_programming) (perhaps with [PostSharp](http://www.sharpcrafters.com/) – Justin Feb 20 '12 at 18:34
  • That is precisely my point. He wants to access a theoretically arbitrary variable. If it's a field, this code will work, if it's a property, other code will work, if it's a parameter, other code could work. You don't have a very generalized solution. – McKay Feb 21 '12 at 14:50
-1

You can use a string in Control.Find function like below statement.

ComboBox comboBoxElement  = (ComboBox)this.Controls.Find("comboBoxNameThatYouSearch", true)[0];
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
erdemu
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 07 '22 at 20:34