So I've created a class that inherits DynamicObject
public class MyDynamicObject : DynamicObject{
private Dictionary<string, object> Fields = new Dictionary<string, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return Fields.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
Fields[binder.Name] = value;
return true;
}
}
And call this class here
public class Program
{
public static void Main()
{
dynamic person = new MyDynamicObject();
person.firstname = "Hello";
Console.WriteLine(person.firstname);
}
}
Of course this will work. But I need to create properties from a string array like
string[] fields = new string[]{"taxid","newcol","addrs","gender"};
dynamic person = new MyDynamicObject();
foreach(var f in fields)
{
person.f = "hello";
}
So the output will be person.taxi, person.newcol, person.addrs, person.gender
Is this possible?
Okay so based on the suggestion of @Jon Hanna, I came up with a solution that fits my requirements. I created a new Add method which accept a name. Below is the updated code I used.
Then I just call it like this.