-1

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; 
tereško
  • 58,060
  • 25
  • 98
  • 150
AHmedRef
  • 2,555
  • 12
  • 43
  • 75

2 Answers2

2

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;
Craig W.
  • 17,838
  • 6
  • 49
  • 82
  • I misunderstood that can you explain it to me ! – AHmedRef Mar 26 '14 at 16:04
  • You'll have to be precise in your question. I already explained it in the original post. If you have a specific question I'd be happy to try to answer it. – Craig W. Mar 26 '14 at 16:08
  • What you suggest dosen't work for me @Craig because as i said i wannna create object properties based on String text like this : object obj; obj.makePropperty("username","user1"); obj.makePropperty("firstName","jnah"); obj.makePropperty("year",2014); – AHmedRef Mar 26 '14 at 16:11
1

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"));
markpsmith
  • 4,860
  • 2
  • 33
  • 62