Can we create dynamic variable in C#?
I know my below code is threw error and very poor coding. But this code have small logic like create dynamic variable
var name=0; for(i=0;i<10;i++)// 10 means grid length { name+i=i; } var xx1=name1; var xx2=name2; var xx3=name3;
Is it possible in c#? Create dynamic variable in c#? and change the variable name in c#? and concatenate the variable name in c#(like we can concatenate any control id or name)...
Why I need the dynamic variable name (scenario):
var variablename="" var variablename0=No; var variablename1=Yes; var variablename2=No;
. . .
I have a gridview
with multiple rows. And I need assign server side variable to every row. So I need set of variables in server side. the only I can set Text=<%# variablename+rowCount%>
for every template field.
This rowCount
means every grid row index.
If the grid has 2 rows, Then rowCount
values are 0,1,2
Now I need to change the variablename
to variablename0,variablename1,variablename2
dynamically for separate row.
Use an Array of Variables The simplest JavaScript method to create the dynamic variables is to create an array. In JavaScript, we can define the dynamic array without defining its length and use it as Map. We can map the value with the key using an array and also access the value using a key.
Use the for Loop to Create a Dynamic Variable Name in Python Along with the for loop, the globals() function will also be used in this method. The globals() method in Python provides the output as a dictionary of the current global symbol table.
There are no dynamic variables in Java. Java variables have to be declared in the source code1. Depending on what you are trying to achieve, you should use an array, a List or a Map ; e.g. It is possible to use reflection to dynamically refer to variables that have been declared in the source code.
A dynamic variable is a variable you can declare for a StreamBase module that can thereafter be referenced by name in expressions in operators and adapters in that module. In the declaration, you can link each dynamic variable to an input or output stream in the containing module.
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"]; } } }
No. That is not possible. You should use an array instead:
name[i] = i;
In this case, your name+i
is name[i]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With