Click here to Skip to main content
14,743,331 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
I use DynamicObject class to create properties dynamically. In mail method I use it like this.(With reference to http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject%28VS.95%29.aspx[^])

dynamic person = new DynamicProp();
p.FirstName = "AA";
p.age = 10;


But in my person table can be altered at the runtime by the user. He can add more fields as he wants to keep the person details.
Then I need to create properties according to the person table's columns. In this case how can I create property using table field. In this example I must know the property name to create the property. But I don't know what field names has created by the user.
Posted
Updated 9-Jul-20 3:06am
v3

Hi;
I rewrote your person class; here it is:
public class Person : DynamicObject
{
    public string Name { get; set; }
    public string Address { get; set; }
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();
    public int Count
    {
        get
        {
            return dictionary.Count;
        }
    }
    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        string name = binder.Name;
        return dictionary.TryGetValue(name, out result);
    }
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;
        return true;
    }
    public void AddProperty<TTValue>(string key, TTValue value = default(TTValue))
    {
        dictionary[key] = value;
    }
    public void AddProperty(string typeName, string key, object value = null)
    {
        Type type = Type.GetType(typeName);
        dictionary[key] = Convert.ChangeType(value, type);
    }
}

You can use it like this:
dynamic p = new Person();
p.Name = "john";
p.Address = "address1";
p.Manager = "My Manager";
p.AddProperty<DateTime>("BirthDate", DateTime.Now);
p.AddProperty("System.String", "Weigth", "70 kg");
Console.WriteLine("My name is {0}\nMy manager is {1}\nMy birth Date is {2}",
    p.Name, p.Manager, p.BirthDate);
string w = p.Weigth;
Console.WriteLine("My Weigth is: " + w);
Console.ReadKey();


Hope i have been helpful.
   
v6
Comments
Sanyon_d 13-Jun-11 6:47am
   
Thanks for the reply. I'm having the problem like this. I create the person object like this.

<pre> Person person=new Person("Sam","Lewis") </pre>

It has properties like this.
person.Dob
person.Address

But now I want to add properties like this and set the values at the run time after creating the object.
person.Age
person.Sex
lampiclobe 13-Jun-11 7:50am
   
Hello;
Sorry for taking your question wrong.
Implement your class like this:
<pre lang="cs">
class Person : DynamicDictionary
{
public string Dob;
publis string Address;
}
//Now you can use it anywhere like this:
public static int Main(string[] args)
{
Person p = new Person();
p.Address = "Some Address"; //existing property
p.Manager = "Bob Wilkinson" //new property
}
</pre>

Note:DynamicDictionary class is the class in MSDN link you gave.
Sanyon_d 14-Jun-11 5:41am
   
Thanks for the reply. Here you know the property name Manager. But in my case I don't know the property name. According to the string value in the table I have to create the property.
eg.
p.AnyStringName="anyvalue";

Like that I have to create all the properties that property name stored in the table.
lampiclobe 14-Jun-11 8:20am
   
Hi sanjeewabdissa
Now i see.
You want to add new properties as text based. Rereferencing the DynamicDictionaty Class here is your solution:
Add these lines to the end of the Person Class i gave above:
public void AddProperty(string propertyName, object anyValue=null)
{
dictionary[propertyName.ToLower()] = anyValue;
}

Hope have been helpful.
Sanyon_d 16-Jun-11 5:54am
   
Can I take help from icustomtypedescriptor interface
lampiclobe 17-Jun-11 11:50am
   
you'd better look at this link:
http://msdn.microsoft.com/en-us/magazine/cc163816.aspx
Sanyon_d 19-Jun-11 23:57pm
   
Fantastic work dr.ozgur.sonmez. Your edited example works nicely for me.Thank you very much. Just another little problem still I'm having. I'm creating List of person objects and bind it to a datagrid view. In grid Name,Address shows with valus. But dynamically created properties (BirthDate) are not showing the values. It only show the property name in the column header.How can I over come this. Thanks again for your kind help.
BobJanova 20-Jun-11 6:49am
   
To get data binding to see additional properties, you need to implement ITypeDescriptor and in particular GetProperties.
lampiclobe 20-Jun-11 14:51pm
   
I updated solution. Thanks indeed.
balajitk 30-Mar-12 1:53am
   
hi lampiclobe,
i've created the same class by using your code.
dynamic p = new Person();
p.Name = "john";
p.Address = "address1";
p.Manager = "My Manager"; p.AddProperty("BirthDate", DateTime.Now); p.AddProperty("System.String", "Weigth", "70 kg");
Console.WriteLine("My name is {0}\nMy manager is {1}\nMy birth Date is {2}", p.Name, p.Manager, p.BirthDate);
string w = p.Weigth;
Console.WriteLine("My Weigth is: " + w);
Console.ReadKey();
but when i call this class property using dynamic it shows an error like follows

Error 202 One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?
lampiclobe 9-Dec-14 0:21am
   
Years has passed! Oh my goodness..You'Re right balajitk. You should add references to the dlls you underlined
Well, I will suggest to use ExpandoObject class, which allows you to create dynamic members of a class.

Please refere below links for more details.

http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx[^]

Perform Reflection and XML Traversing Using the dynamic Keyword in C#[^]

I hope, this will surely help you.

Thanks :)
   
ExpandoObject[^], an implementation of IDynamicMetaObjectProvider (just like DynamicObject), also implements IDictionary<string,Object>. Assuming that you know the names of the columns added to the table, and that you can fetch their values, you can use the dictionary syntax to set properties, like this:
var person=new ExpandoObject();

// You can choose between the regular property syntax
person.FirstName="Joe";

// ...and the square bracket dictionary syntax:

person["MyDynamicallyAddedProperty"]="Value of my dynamically added property";
   
Comments
CHill60 9-Jul-20 12:40pm
   
By posting this as a comment only a few people will see it. Why not post your own question using the red "Ask a Question" link at the top of this page. More people will see it which makes it more likely you will get an answer. You might need to try to make your problem statement a bit clearer though

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900