c# reusable property to be called passed by lambda

327 views Asked by At

I'm trying to write a method that would take an object with property name as a lambda parameter, and use it on passed object, but also use it on another, new object of the same type created inside that method.

The goal is to use the same property on both objects. The property name should be passed as a parameter to the method (lambda expression).

Let me show what I've written so far (doesn't compile):

Object to be used:

public class ObjectMy
{
  public string Prop1 {get; set;}
}

Method in another class to be used with above object:

public class TestClass1
{
    public void DoSomethingOnProperty(Expression<Func<ObjectMy,string>> propertyName)
    {
        var object1 = new ObjectMy();
        var propertyNameProp = propertyName.Body as MemberExpression;
        propertyNameProp.Member = "Test string"; // error Member is readonly

        //DoSomethingOnProperty(object1.thesameproperty...)

    }
}

I want to set passed in method's name property of ObjectMy's instance to "Test string" and then recursively call DoSomethingOnProperty on another, new instance of ObjectMy, and use the same property name as given in the first call to DoSomethingOnProperty.

I'd like to call it like

DoSomethingOnProperty(obj=>obj.Prop1);

Thanks.

1

There are 1 answers

0
mitsbits On BEST ANSWER

Try changing your method like this:

public void DoSomethingOnProperty<T>(Expression<Func<T, dynamic>> propertyName) where T : class, new()
    {
        var object1 = Activator.CreateInstance(typeof(T));
        var methodName = (propertyName.Body as MemberExpression).Member.Name;
        var propertyInfo = typeof(T).GetProperty(methodName);
        typeof(T).GetProperty(methodName).SetValue(object1, Convert.ChangeType("Test string", propertyInfo.PropertyType));

        //DoSomethingOnProperty(object1.thesameproperty...)

    }

you could use it like

DoSomethingOnProperty<ObjectMy>(x => x.Prop1);