Search This Blog

Thursday, July 21, 2016

How to create C# variables dynamically?

In some cases we have scenario like have to create variables dynamically.To achieve this we have to use dictionary.I have shown some sample example with this post.

Sample variables
String strvar_1=null;
String strvar_2=null;
String strvar_3=null;

strvar_1="DynamicValue_1";
strvar_2="DynamicValue_2";
strvar_3="DynamicValue_3";

//below is the code to dynamically create above variable and assigning the values 

//Create dictionary to create variable names
//In this first string would be the variable name and second string would be the value for that variable we are assigning null initially
Dictionary<String, String> dynstr = new Dictionary<String, String>();
for(int i = 1; i < 4; i++) {
  dynstr .Add("strvar_" + i, null);
  }

//we are assigning value to those variables
  for(int i = 1; i < 4; i++) {
    dogs["strvar_" + i] = "DynamicValue_" + i;
  }

No comments:

Post a Comment