1

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]      // ??
  }
2
  • 2
    I think you mean "property", not attribute which has its own meaning in c#. And yes, you can use Reflection to get a Property value by name. Commented May 13, 2017 at 12:12
  • To access a property exactly like you're referring to, you'd need some type of Dictionary<string, object> which lets you obtain a value through the key accessor public TValue this[TKey key] { get; set; } Commented May 13, 2017 at 12:38

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.