Can we create variables at run time - c#

In c# why is it not allowing to create variable names dynamically? I am trying something like this:
for (int i = 0; i < ceoList.Count; i++)
{
List<VP> "vp" + i = new List<VP>();
}
I want to generate variable names at run time. Like "vp" + i here.

You don't want to create variable names at run time, you want to create data structures.
List<List<VP>> vps = new List<List<VP>>
for (int i = 0; i < ceoList.Count; i++)
{
vps.Add( new List<VP>());
}

What you are trying to accomplish is not a valid programming syntax, and will not compile in any imperative programming language compiler!
What you want is a way to name references to a set of objects of the type List, so to achieve that I would recommend you to check it out HashTables in the namespace System.Collections.
Hashtable vpTable = new Hashtable();
for (int i = 0; i < ceoList.Count; i++)
{
vpTable.add("vp" + i, new List());
}

Related

How to create arrays with different names in C#?

I'm currently working on a game (console application) with 25 Chunks, that are 5x5. All Chunks are in a List(5x5) witch is the Level in the end.
I do not want to declare all arrays. I would like to write a method in witch the arrays will be declared but with changing names.
For example:
- ac_Array_1
- ac_Array_2
static void Level()
{
List<char[,]> ol_Level = new List<char[,]>();
}
static void Spielblock()
{
int i_Stelle = 1;
string s_ArrayName = "ac_Chunk_" + i_Stelle;
i_Stelle++;
char[,] /*NAME*/ = new char[5, 5];
}
Try something like this:
int numOfLevels = 5;
Dictionary<string, char[,]> ol_Level = Enumerable
.Range(1, numOfLevels)
.ToDictionary(k => $"ac_Chunk_{k}", v => new char[5,5]);
ac_Chunk = ol_Level["ac_Chunk_1"];//char[5,5]
for (int i_Row = 0; i_Row < ac_Chunk.getLength(0); i_Row++)
{
for (int i_column = 0; i_column < ac_Chunk.getLength(1); i_column++)
{
ac_Chunk[i_Row, i_column] = '#';
}
}
...
levels:
ac_Chunk_1, ac_Chunk_2, ac_Chunk_3, ac_Chunk_4, ac_Chunk_5
n.b. using System.Linq and c# 6.0 $ interpolation
To have a dynamic variable name like you are requesting is not a simple thing to accomplish.
Generally, variable names are known at compile time, and the compiler can make optimizations using that information. What you are requesting would keep that from happening.
So the suggestions that you are seeing: create a variable, such as a dictionary, known when compiling and writing the code. Make that variable one that can dynamically expand to contain as many "chunks" as you'd like. And with a Dictionary<string, char[,]> you can even give each of those chunks a name. They won't be individual variable names, but it will let you access them by string/name and iterate through the collection in different ways.
To add a detail to Johnny's answer, at any point you can use
var ac_chunk = ol_Level["ac_Chunk_1"];
if you want to repeatedly access an individual chunk.
Or, even easier, just keep using ol_Level[$"ac_Chunk_{chunkNumber}"]

creating a custom list windows phone 8.1

here is the code adding data to the list, after which i return the list. Problem is that the last set of data seems to be overwriting everything else in the list
for (int k=0; k < jsonObject["mydetails"].GetArray().Count; k++)
{
//add the corresponding data from the sample array
obj.accountNumber = jsonObject["mydetails"].GetArray()[k].GetObject()["id"].GetString();
obj.accountName = jsonObject["mydetails"].GetArray()[k].GetObject()["name"].GetString();
obj.accountBall = jsonObject["mydetails"].GetArray()[k].GetObject()["age"].GetString();
mylist.Add(obj);
}
Your code isn't adding any new objects to the list, it modifies and adds the same object. In the end, the list contains X references to the same object instance.
In general it is consider bad practice to declare a variable outside the scope in which it is used. You could have avoided this problem by writing:
var myArray=jsonObject["mydetails"].GetArray();
for (int k=0; k < myArray.Count; k++)
{
var myJsonObject=myArray[k].GetObject();
var obj=new MyAccountObject();
obj.accountNumber = myJsonObject["id"].GetString();
...
}
Notice that instead of calling GetArray() and GetObject() in each line (essentially doing the job of extracting the array multiple times) I stored them in separate variables. This will result in far less CPU and memory usage.
You always add the same object obj to the list. You need to create a new in the top of the loop.
for (int k=0; k < jsonObject["mydetails"].GetArray().Count; k++)
{
obj = new ObjectType(); // you know better the type of the object you want to create.
//add the corresponding data from the sample array
obj.accountNumber = jsonObject["mydetails"].GetArray()[k].GetObject()["id"].GetString();
obj.accountName = jsonObject["mydetails"].GetArray()[k].GetObject()["name"].GetString();
obj.accountBall = jsonObject["mydetails"].GetArray()[k].GetObject()["age"].GetString();
mylist.Add(obj);
}
Without the the line obj = new ... you change the properties accountNumber, accountName and accountBall of the same object instance. At the end you add always that object reference to the list. So it seems that the last run of the loop changes all objects.

How can I compose variables names through loop in C#?

I have rewritten this question because not everyone understood. Hope it's ok, it's the same main problem.Very sorry
I have a winform with 15 progress bars called: "baraClasa1", "baraClasa2", "baraClasa3" ... "baraClasa15". I have to assign the .VALUE property (as in int) to all of them, from some database records. (The records access the different values from different time periods)
I was thinking that maybe it is possible to use a loop to assign the .Value property to all of them by doing something like:
for(int i=0; i<value; i++)
{
"baraClasa+i".Value = 20 + i;
}
Is it possible to compose the name of the variables like that?
I don't know much about dictionaries, lists but looking into. If nothing works il just do the ugly:
int value = 20;
baraClasa1 = value;
baraClasa2 = value +1;....
Thank you for all help
You have to do a little reflection.
public string variable0, variable1, variable2, variable3, variable4, variable5;
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 6; i++)
{
//pretending my variable names are variable1, variable2.. ("variable" is NOT an array! just the "assign" variable)
System.Reflection.FieldInfo info = this.GetType().GetField("variable" + i.ToString());
// replace "testing" with the value you want e.g. assign[i]
info.SetValue(this, "testing");
}
// Do something with your new values
}
No need to use reflection with the updated question. The control collection has a built in find for getting a control by the name string.
for (int i = 0; i < 6; i++)
{
ProgressBar bar = (ProgressBar)this.Controls["baraClasa" + i.ToString()];
bar.Value = 50;
}
This is a design problem. Create a collection for items with common use (like progress bars for that matter) and iterate over the collection to perform actions on them.
If these are prorgress bars you might want to use an event-driven design (another link) to update their progress, meaning that each time a bar has made some progress, the event for the progress will send an update only to that bar, and not iterate over the entire list.
You may want to read an introduction to event driven programming in C# before re-factoring your code.
It really isn't possible in C# to refer to local variables in a dynamic fashion as you are trying to do. Instead what you would do in C# is store the value in a dictionary where the key can be generated in a dynamic fashion.
For example let's say all of your variable1, variable2, ... variableN were of type int. Instead of
int variable1 = 0;
int variable2 = 0;
...
int variableN = 0;
You would instead do the following
Dictionary<string, int> map = new Dictionary<string, int>();
for (int i = 0; i < N; i++) {
map[i.ToString()] = 0;
}
If the values are a of a fixed number and always linear in progress it may make sense to use an array instead of a dictionary
int[] array = new int[N];
for (int i = 0; i < N; i++) {
array[i] = 0;
}
You can't do it that way. You need an array. Every time you notice yourself having a variable2, you need an array. You may not know it yet, but you do.
No, you can't do it in C#, it's syntactically impossible. But if you want access form controls which has different names like this you can do the following:
for(int i=0; i<20; i++)
{
var name = "variable" + i;
this.Controls[name].Text = "etc..." // here you can access your control
}
If you want to have names for your objects, use a dictionary:
Dictionary<string, type> myDict = new Dictionary<string, type>()
string naming = "MyPattern{0}";
for (int i = 0; i <value; i++) {
myDict.add(string.Format(naming, i.ToString()), assign[i]);
}
And then you can access them by doing, for example:
myDict["MyPattern1"]
However, I suggest you would be better off using a collection like a List or array.
Arrays, lists, dictionaries, hash maps... collections in general are what you would use here. For example, if you have a dictionary, then it consists of key/value pairs. So a dictionary might look like this:
var variable = new Dictionary<int, string>();
Where the int is the key for any given entry, and the string is the value. You'd assign values in something like this:
for(int i = 0; i < value; i++)
variable.Add(i, assign[i]);
Of course, since i is just an incrementing integer in this case (unless you have some other key in mind?), then it works just as well as an indexer on a list. Something like this:
var variable = new List<string>();
for (int i = 0; i < value; i++)
variable.Add(assign[i]);
In both cases, you'd access the assigned value later by referencing its key (in a dictionary) or its index (in a list, or any array):
var someOtherVariable = variable[x];
Where x is an integer value present in the dictionary's keys or in the array's size.
If you can put names of all variables in an array such as 'variable', and they are unique, you can try to use dictionary :
Dictionary<object, object> dictionary = new Dictionary<string, object>();
for(int i=0; i<value; i++)
{
dictionary.Add(variable[i], assign[i]);
}

Taking arbitrary list of objects and initializing all of them

bgList.Add(bg1);
bgList.Add(bg2);
bgList.Add(bg3);
bgList.Add(bg4);
bgList.Add(bg5);
//Initialize all background objects
for (int i = 0; i < bgList.Count; i++)
{
bgList[i] = new Sprite();
bgList[i].Scale = 2.0f;
}
Is this a legitimate way to do this? Basically, the question boils down to "Can I initialize a list of objects using a for loop?
I'm getting "This Object will never not be null" warnings on the bg1, bg2, bg3, bg4, and bg5 objects, and that's making me wonder if this technique isn't allowed.
These statements are not equivalent:
bg1 = new Sprite();
and
bgList.Add(bg1);
bgList[0] = new Sprite();
The latter will not assign the reference to the new instance to bg1. It just stores the new instance in the 0th location.
So using a collection and loop to instantiate a number of variables is not a working short-cut. You have to instantiate each variable explicitly, or use an array or collection from the first place.
a foreach would be easier for sure, and y you should be able to do it, but imo you can also add the items in the loop something like.
for (int i = 0; i < bgList.Count; i++)
{
var bglistitem = new Sprite()
bhlistitem.Scale = 2.0f;
bgList.Add(bglistitem);
}

How can i construct a variable name in code from a string?

I have a number of variables named test1....test10 they are all declared as a string.
what I want to do is access them from inside a loop using the loop counter something like this:
string test1;
//...
string test10;
for (int i = 1; i < 10; i++)
{
test + i.ToString() = "some text";
}
any idea how I could do this?
this is a WPF .net 4 windows App.
Simple answer: don't have 10 variables, have one variable which is a collection:
List<string> test = new List<string>();
for (int i = 1; i < 10; i++)
{
test.Add("some text");
}
Having lots of variables which logically form a collection is a design smell.
(If you really have to do this, you could use reflection. But please don't.)
You simply can't, use a List or a String-Array for this purpose.
List
List<String> myStrings = new List<String>();
for (Int32 i = 0; i < 10; i++)
{
myStrings.Add("some text");
}
String-Array
String[] myStrings = new String[10];
for (Int32 i = 0; i < myStrings.length; i++)
{
myStrings[i] = "some text";
}
Try adding them to an array of string[] or simply create a List<string> list = new List<string>();.
With the list, you can iterate easily.
This is not really possible, unless you use the dynamic keyword, and then you will get a property instead of a true variable. Take a look at ExpandoObject, it will allow you to add properties based on a string variable.
In your case, as other have said, you really should use a List<string>
For something as simple as 10 items, an array is the best way to go. Fast and easy.

Categories

Resources