Can an object in C# return the value of one of its attributes if the name of the desired attribute is provided as a string at runtime?
myObject["price"]
Let's say we have this object:
public class Widget
{
public Widget(){}
public DateTime productionDate {get;set;}
public decimal price {get;set;}
}
and this SqlCommand parameter definition:
SqlCommand c = new SqlCommand();
c.Parameters.Add(new SqlParameter("@price", SqlDbType.SmallMoney,0,"price"));
Elsewhere in the code in a different scope, the user has clicked on a [Save Record] button and now we need to bind the values in a widget object to the parameters of an update command. We have a reference to that SqlCommand in variable command:
foreach (SqlParameter p in command.Parameters)
{
// assume `parameter.SourceColumn` matches the widget attribute name
string attributeName = p.SourceColumn;
p.Value = widget[attributeName] // ??
}
Dictionary<string, object>which lets you obtain a value through the key accessorpublic TValue this[TKey key] { get; set; }