Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

ExpandoObject Add PropertyName and PropertyValue Dynamically

//Here's a method that accepts both a property name and a property value then adds them both to an ExpandoObject:
public ExpandoObject CreateDynamicCustomer(string propertyName, string PropertyValue)
{
  dynamic cust = new ExpandoObject();
  ((IDictionary<string, object>)cust)[propertyName] = PropertyValue;
  return cust;
}

// How it is use
dynamic cust = CreateDynamicCustomer("FullName", "Peter Vogel");
string fname = cust.FullName;

// retrieve the properties added dynamically 
foreach (KeyValuePair<string, object> kvp in ((IDictionary<string, object>) cust))
{
  if (!kvp.Value.GetType().Name.Contains("Action"))
  {
    foreach (KeyValuePair<string, object> kvp in ((IDictionary<string, object>) cust))
    {
      string PropertyWithValue = kvp.Key + ": " + kvp.Value.ToString();
    }
  }
}
Source by visualstudiomagazine.com #
 
PREVIOUS NEXT
Tagged: #ExpandoObject #Add #PropertyName #PropertyValue #Dynamically
ADD COMMENT
Topic
Name
7+9 =