user2915058
user2915058

Reputation: 43

Accessing a class field using a string

I have a class name DB.IFCArray which have plenty of fields in it (name, description etc), I want to implement a function that goes to the DB.IFCArray.field and do stuff..

public static bool if_is_a(DB.IFCArray object1, string field, string value)
        {            
            if (object1.field == value) // this ofc not working, but hope you get the idea
            return true;

            return false;
         }

Upvotes: 0

Views: 173

Answers (2)

Stephen Byrne
Stephen Byrne

Reputation: 7485

You can of course use Reflection

//get the property indicated by parameter 'field'
//Use 'GetField' here if they are actually fields as opposed to Properties
//although the merits of a public field are dubious...
       var prop = object1.GetType().GetProperty(field);
//if it exists
        if (prop!=null)
        {
          //get its value from the object1 instance, and compare
          //if using Fields, leave out the 'null' in this next line:
          var propValue = prop.GetValue(object1,null);

          if (propValue==null) return false;
          return propValue;
        }
        else
        {
          //throw an exception for property not found
        }

But as CodeCaster mentioned above, I'd recommend you take a look at your design and see if this is really necessary. What is the bigger picture here? Unless you absolutely 100% will not know the property names until runtime, there's almost always a better way...

Upvotes: 1

Rashedul.Rubel
Rashedul.Rubel

Reputation: 3584

I think error is showing due to type error in the if (object1.field == value) statement. use reflection to get type of the field and compare the value according to the type.

Hope this helps, Thanks.

Upvotes: 0

Related Questions