Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to Attributes using a String

Tags:

c#

Given a string with the same name of an object field, how can I get the reference to the object field?

For example, say I pass in a string called "field1" to the GetFieldByStr method, and the object has an field name field1, how can I get a reference to the field1 object? I'm assuming using reflection somehow.

class Example {
   private FieldExample attr1;

   void GetFieldByStr(String str) {
      // We get passed in "field1" as a string, now I want 
      // to get the field1 attribute.
   }
}
like image 252
Steve Avatar asked Jan 24 '26 21:01

Steve


1 Answers

You need to use Reflection:

FieldInfo field = typeof(Example).GetField(str);
object value = field.GetValue(this);

(For properties, use PropertyInfo)

Note that value is an object; in order to do anything useful with it, you'll need to cast it to some class or interface (or use dynamic in C# 4).

like image 116
SLaks Avatar answered Jan 27 '26 11:01

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!