Tufan Chand
Tufan Chand

Reputation: 752

Get the value from object of a class by property name dynamically in c#

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.

Upvotes: 0

Views: 830

Answers (1)

Sean
Sean

Reputation: 62472

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);
}

Upvotes: 3

Related Questions