forum

Home / DeveloperSection / Forums / How can I pass a property in via a lambda expression?

How can I pass a property in via a lambda expression?

Anonymous User 2276 04-Feb-2014

There are some unit tests on my project where we want to be able to set some properties that have private setters. Currently I'm doing it via reflection and this extension method:

public static void SetPrivateProperty(this object sourceObject, string propertyName, object propertyValue)
{
    sourceObject.GetType().GetProperty(propertyName).SetValue(sourceObject, propertyValue, null);
}
Assuming I had a TestObject like this:
public class TestObject
{
    public int TestProperty{ get; private set; }
}

I can then call this in my unit tests as follows:

myTestObject.SetPrivateProperty("TestProperty", 1);

However, I'd like to have validation of the property name at compile time, and thus I'd like to be able to pass the property in via expression, like this:

myTestObject.SetPrivateProperty(o => o.TestProperty, 1);

How can I do this?


c# c# 
Updated on 04-Feb-2014
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By