is there any possibility to make object properties using String values in C# ? like this :
object obj;
obj.makePropperty("username","user1");
obj.makePropperty("firstName","jnah");
obj.makePropperty("year",2014);
String getValue = obj.username;
is there any possibility to make object properties using String values in C# ? like this :
object obj;
obj.makePropperty("username","user1");
obj.makePropperty("firstName","jnah");
obj.makePropperty("year",2014);
String getValue = obj.username;
I think ExpandoObject was introduced in .NET 4.0. You could use that.
public dynamic MyObject { get; private set; }
MyObject = new ExpandoObject();
((IDictionary<string, object>)sourceObjectCustomFieldsExpando)Add(
<PropertyName>, <Value> );
The only advantage of this over a dictionary that later on you can access the properties using dot notation.
((IDictionary<string, object>)MyObject)Add( "Foo", "bar" );
...
var value = MyObject.Foo;
Using anonymous types, you could create a new object like this:
var newObj = new { username = "user1", firstName = "jnah", year = "2014"};
Or if you had a class to represent your object looking like this:
public string username {get; set;}
public string firstName {get; set;}
public string year{get; set;}
var newObj = new myObj{ username = "user1", firstName = "jnah", year = "2014"};
Update: You could also use a list of Dictionary or KeyValuePairs:
var objList= new List<KeyValuePair<string, string>>();
list.Add(new KeyValuePair<string, int>("username ", "user1"));
list.Add(new KeyValuePair<string, int>("firstName", "jnah"));
list.Add(new KeyValuePair<string, int>("year", "2014"));