How to change PropertiesName dynamically [Resolved]

Posted by Santosh4u under C# on 2/24/2016 | Points: 10 | Views : 556 | Status : [Member] | Replies : 2
Hi
how do i set properties name dynamically.

public sealed class CompanyDetails
{

string _Jan = string.Empty;
string _Feb = string.Empty;
string _Mar = string.Empty;
public string Jan { get { return _Jan; } set { _Jan = value; } }
public string Feb { get { return _Feb; } set { _Feb = value; } }
public string Mar { get { return _Mar; } set { _Mar = value; } }
}
based on passing year the propertyname should change, if passing 2016 then "jan" propertyname should be "Jan2016" same as feb and march.

Thanks




Responses

Posted by: Rajnilari2015 on: 2/24/2016 [Member] [Microsoft_MVP] [MVP] Platinum | Points: 50

Up
0
Down

Resolved
@Santosh4u,
Try this ( just an example for demonstration) - using Dictionary Object

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;
}
}
}


Other option should be Expando Object ( http://www.codeproject.com/Articles/121472/An-introduction-to-Expando-Object-Dotnet )

Hope this helps


--
Thanks & Regards,
RNA Team

Santosh4u, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Amatya on: 2/24/2016 [Member] Silver | Points: 25

Up
0
Down
Simple and good.. Nice code @Rajni

Feel free to share informations 9731764134
mail Id ' adityagupta200@gmail.com
Thanks

Santosh4u, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response