0

I want to write a method that should return the value from an object for the specified property.

public class MyClass
{
    public int a { get; set; }
    public int b { get; set; }
    public int c { get; set; }
    public int d { get; set; }
}


public int GetValue(string field)
{
     MyClass obj=new MyClass();
     obj=FromDb(); //get value from db
     dynamic temp=obj;
     return temp?.field;
}

The above code is only to demonstrate to what I am looking for.

Here I want to pass the property name (i.e a/b/c/d as per my above code) as an input to the method GetValue and it should return the value of that property.

This code is compiling successfully, but in run time it will search for the property name field not the value of field variable.

Any suggestions or workaround will be appreciated.

1 Answer 1

3

You can use reflection to get the value:

public int GetValue(string field)
{
     MyClass obj = new MyClass();
     obj = FromDb(); //get value from db
     var property = obj.GetType().GetProperty(field);
     return (int)property.GetValue(obj);
}
Sign up to request clarification or add additional context in comments.

4 Comments

I was suggesting the same but since you answer came up before mine I just upvote your ;)
Thank you so much I am going to try it out, just worrying about performance will it have any impact?
@TufanChand - Yes, there will be a performance hit. Whether it will impact your application is hard to say. You'll probably want to measure the performance and make sure you're happy with it.
@Sean, ok understood, I will take care of that. Thank you very much for your help.

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.