Note that there are some explanatory texts on larger screens.

plurals
  1. PODynamically create and set members/properties of class at runtime
    primarykey
    data
    text
    <p>How can I create and set members/properties of a class dynamically at runtime.</p> <p>Ref: <a href="http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember(v=vs.110).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember(v=vs.110).aspx</a></p> <p>I tried to modify the idea to suit my requirements but unable to do it.</p> <p>I am required to set the class members at runtime, means I would fetch the <code>Key</code> and <code>Value</code> from the database and my class will be completely dynamic with no members defined before runtime, but all of them is fetched from database during runtime.</p> <p>So here goes my code (Taken from MSDN):</p> <pre><code>public class DynamicObjDictionary : DynamicObject { // The inner dictionary. Dictionary&lt;string, object&gt; dictionary = new Dictionary&lt;string, object&gt;(); public int Count { get{return dictionary.Count;} } public override bool TryGetMember(GetMemberBinder binder, out object result) { string name = binder.Name.ToLower(); return dynDict.TryGetValue(name, out result); } public override bool TrySetMember(SetMemberBinder binder, object value) { dynDict[binder.Name.ToLower()] = value; return true; } } } </code></pre> <p>The code that initializes and defines the members/properties of the class</p> <pre><code>dynamic DynObj = new DynamicObjDictionary(); DataSet ds = new DataSet(); ds = GetObjectProperties() // returns dataset having the properties as key and value pair; if (ds.Tables["PropTable"].Rows.Count &gt; 0) { foreach (DataRow dr in ds.Tables["PropTable"].Rows) { string KeyName = dr["KeyName"].ToString(); string ValueName= dr["ValueName"].ToString(); //---I want that in place of fldName the actual value from dr is added to the class - currently it returns DynObj.KeyName only. DynObj.KeyName = ValueName; // Means if current dr["KeyName"].ToString() has "Property1" // And dr["ValueName"].ToString() has "PropertyValue" // The DynObj should be like DynObj.Property1 = "PropertyValue" } } </code></pre> <p>And another problem is that I want all the properties to be set after the above initialization so that I can access them like a class object that is hard-coded. Current code only retails the last property i.e. the value of the last row of the dataset.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload