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.
Try changing your method like this:
you could use it like