Reputation: 8919
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] // ??
}
Upvotes: 1
Views: 1070
Reputation: 191
Addition to Crowcoder:
You can use reflection and call Type.GetProperty("nameOfProperty") to get a PropertyInfo on which you can call the GetMethod property.
The GetMethod property returns a MethodInfo on which you can call the Invoke method to retrieve the value of the property.
For instance:
var propertyInfo = myObject.GetType().GetProperty("price");
var getMethod = propertyInfo.GetMethod;
string value = getMethod.Invoke(myObject, null) as string
Edit:
After reading your question again, I realise, I didn't answer your question. You should/could combine my previous answer with an Indexer: https://learn.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/indexers/index
Upvotes: 2