Program to create/write and set properties at runtime in C#

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 630
The below program will do so

using System.Collections.Generic;

namespace ConsoleApplication1
{

class DynamicProperties
{
Dictionary<string, object> properties = new Dictionary<string, object>();

public object this[string name]
{
get
{
if (properties.ContainsKey(name))
{
return properties[name];
}
return null;
}
set
{
properties[name] = value;
}
}

}

class Program
{
static void Main(string[] args)
{
int year = 2015;
int month = 3;

var year_MnthProperty = new DynamicProperties();

//set the property names with values
switch (month)
{
case 1:
year_MnthProperty[string.Concat(GetMonthName(month), year)] = 100; break;
case 2:
year_MnthProperty[string.Concat(GetMonthName(month), year)] = 200; break;
case 3:
year_MnthProperty[string.Concat(GetMonthName(month), year)] = 300; break;
case 4:
year_MnthProperty[string.Concat(GetMonthName(month), year)] = 400; break;
case 5:
year_MnthProperty[string.Concat(GetMonthName(month), year)] = 500; break;
case 6:
year_MnthProperty[string.Concat(GetMonthName(month), year)] = 600; break;
}

//read the property values
var propertyName = string.Concat(GetMonthName(month), year);
var propertyValues = year_MnthProperty[string.Concat(GetMonthName(month), year)];
}

private static string GetMonthName(int month)
{
string monthName = string.Empty;
switch(month)
{
case 1:
monthName = "January"; break;
case 2:
monthName = "February"; break;
case 3:
monthName = "March"; break;
case 4:
monthName = "April"; break;
case 5:
monthName = "May"; break;
case 6:
monthName = "June"; break;
}
return monthName;
}
}
}

Comments or Responses

Login to post response