Is there a way to dynamically name variables?
What I need to do is take a list of variable names from an input file and create variables with those names. Is this p
try this one,user json to serialize and deserialize:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
public class Program
{
static void Main(string[] args)
{
object newobj = new object();
for (int i = 0; i < 10; i++)
{
List<int> temp = new List<int>();
temp.Add(i);
temp.Add(i + 1);
newobj = newobj.AddNewField("item_" + i.ToString(), temp.ToArray());
}
}
}
public static class DynamicExtention
{
public static object AddNewField(this object obj, string key, object value)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string data = js.Serialize(obj);
string newPrametr = "\"" + key + "\":" + js.Serialize(value);
if (data.Length == 2)
{
data = data.Insert(1, newPrametr);
}
else
{
data = data.Insert(data.Length-1, ","+newPrametr);
}
return js.DeserializeObject(data);
}
}
}
No. Use an array, otherwise you can't do this.
Use a Dictionary<string, Variable>
.
e.g.
var vartable = new Dictionary<string, Variable>();
vartable[strLine] = new Variable(input);
I would use some sort of keyed collection, like a hashtable, dictionary, or list of structures with the name. You can then refer to the variable by name:
var value = variableDictionary["MyVariableName"];
var value = variableHashtable["MyVariableName"];
var value = variableList.First(x=>x.Name == "MyVariableName");
There is no other way to dynamically "name" a variable.
You can't do that, but what you're looking to do is begging for a Dictionary use:
Dictionary<object, object> d = new Dictionary<string, object>();
d.Add("Variable1", value1);
d.Add("Variable2", value2);
d.Add("Variable3", value3);
No. You can load them into a Dictionary object, however. This allows you to still reference them (somewhat) using a name, which is a bit easier than using an Index, as you would with an Array or ArrayList.