Create dynamic variable name
C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickTest
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> names = new Dictionary<string,int>();
for (int i = 0; i < 10; i++)
{
names.Add(String.Format("name{0}", i.ToString()), i);
}
var xx1 = names["name1"];
var xx2 = names["name2"];
var xx3 = names["name3"];
}
}
}
How do I name variables dynamically in C#?
Use a Dictionary<string, Variable>
.
e.g.
var vartable = new Dictionary<string, Variable>();
vartable[strLine] = new Variable(input);
C# - Access variable Names dynamically
You should put the variables into a collection, rather than having a different variable with a different name for each. It's technically possible to access the variable in the manor you describe, but it's not what a language like C# is designed to do, and would be very bad practice.
There are several collections to choose from. Here a List
is probably appropriate, an array could work as well.
List<string> urls = new List<string>()
{
"gmail.com",
"ymail.com",
"hotmail.com",
"outlook.com"
};
foreach (string url in urls)
{
//do whatever with the url
Console.WriteLine(url);
}
Passing a variable name dynamically to a function
You can invoke your method by providing its parameters dynamically with use of System.Reflection.
ForExample:
public class SomeClass
{
public void myFunction(ref List<string> myList)
{
}
}
public class SomeOtherClass
{
public List<string> list1 { get; set; }
public List<string> list2 { get; set; }
public List<string> list3 { get; set; }
public void DoSomething(int listNumber)
{
SomeClass someObject = new SomeClass();
var parameter = typeof (SomeOtherClass).GetProperty("list" + listNumber).GetValue(this);
typeof (SomeClass).GetMethod("myFunction").Invoke(someObject, new[] {parameter});
}
}
C# Declare multiple dynamically named variables
Don't try to use dynamically named variables. That's simply not how variables work in C#.
Use an array of lists:
List<string>[] user = new List<string>[infoForUserSessions.Count];
for (int i = 0; i < infoForUserSessions.Count; i++) {
user[i] = new List<string>();
}
If the number of sessions can change, you would use a List<List<string>>
instead, so that you can add lists to it when you add items to the infoForUserSessions
list.
Accessing Variable Names in for Loop dynamically
You should use a List<int>
or an int[]
(array) instead. They exist exactly for this purpose.
You could do "dynamic variable access", in C# but it is not recommended (or rather very strongly discouraged) to do that, it will be error prone.
Example using array :
// definition of the array (and initialization with zeros)
int[] counts = new int[10];
// (...)
for(int j = 0; j < counts.Length ; j++) // note that array indices start at 0, not 1.
{
if (count[j] == 100)
{
...
}
...
}
Here is a similar version with a List<int>
:
List
s are a more flexible, and slightly more complex (they can change during size during execution, while an array is fixed, you'll have to recreate a whole new array if you want to change the size.)
// definition of the list (and initialization with zeros)
List<int> counts = new List<int>(new int[10]);
// (...)
foreach (int count in counts) // You can use foreach with the array example above as well, by the way.
{
if (count == 100)
{
...
}
...
}
For your testings, you can initialize values for arrays or lists like this :
int[] counts = new int[] { 23, 45, 100, 234, 56 };
or
List<int> counts = new List<int> { 23, 45, 100, 234, 56 };
Note that you can use for
or foreach
for both arrays or List
s, actually. It depends wether you need to keep track of the "index" for your code somewhere.
If you have trouble using for
with List
or foreach
with array, just let me know.
I remember when I first learned programming, that I wanted to do something like your count_1 count_2, etc... Hopefully, discovering the notion of arrays and lists changes my would-be-developer mind, opening a whole new area.
I hope this will set you on the right tracks !
Creating dynamic variable names in C#
If you stick to your current design (CSV + dictionary) you could use the ExpandoObject class to get what you are looking for, create a simple factory class:
public static class ObjectFactory
{
public static dynamic CreateInstance(Dictionary<string, string> objectFromFile)
{
dynamic instance = new ExpandoObject();
var instanceDict = (IDictionary<string, object>)instance;
foreach (var pair in objectFromFile)
{
instanceDict.Add(pair.Key, pair.Value);
}
return instance;
}
}
This factory will create an object instance of whatever dictionary you give it, i.e. just one method to create all your different kinds of objects. Use it like this:
// Simulating load of dictionary from file
var actorFromFile = new Dictionary<string, string>();
actorFromFile.Add("Id", "1");
actorFromFile.Add("Age", "37");
actorFromFile.Add("Name", "Angelina Jolie");
// Instantiate dynamically
dynamic actor = ObjectFactory.CreateInstance(actorFromFile);
// Test using properties
Console.WriteLine("Actor.Id = " + actor.Id +
" Name = " + actor.Name +
" Age = " + actor.Age);
Console.ReadLine();
Hopes this helps. (And yes she was born 1975)
Related Topics
What Is the Static Variable Initialization Order Across Classes in C#
How to Sort a String of Text Followed by a Number Using Linq
How to Get the Full Url of the Page I am on in C#
Converting from Ienumerable to List
How to Get the Width and Height of a Multi-Dimensional Array
How to Initialize a List<T> to a Given Size (As Opposed to Capacity)
Passing Arrays by Value and by Reference
JSONserializersettings and ASP.NET Core
How to Name Variables Dynamically in C#
Ews - Access All Shared Calendars
Passing Data to Master Page in ASP.NET MVC
How to Discover the "Path" of an Embedded Resource
The Current Synchronizationcontext May Not Be Used as a Taskscheduler
What's the Difference Between the Webconfigurationmanager and the Configurationmanager
Command to Close an Application of Console
Get Ssid of the Wireless Network I am Connected to with C# .Net on Windows Vista