Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# set property value of property passed to method via Func<T>

Tags:

c#

.net

func

I use this method to get the value of a property in a method:

public static T Decrypt<T>(Func<T> prop, string username, string password)
{
    T value = prop();
    //do cool stuff with t
    return value;
}

I'm looking for a way to do the other way arround, set the value of my property

public static void Encrypt<T>(Func<T> prop, T value, string username, string password)
{
    //do stuff with value
    ??? set prop ???
}

I've searched and tried Expressions, but cloud not get it to work:

public static void Encrypt<T>(Expression<Func<T>> property, T value, string username, string password)
{
    //do stuff with value
    var propertyInfo = ((MemberExpression)property.Body).Member as PropertyInfo;
    propertyInfo.SetValue(property, value);
}
like image 322
Richard Avatar asked Sep 04 '25 01:09

Richard


2 Answers

Youd could change the Encrypt function like this:

public static void Encrypt<T>(Action<T> prop, T value, string username, string password)
{
  // awesome stuff before
  prop(value);
  // awesome stuff after
}

Then call Encrypt :

Encrypt(value => obj.Prop = value, 23, "", "");
like image 145
Wolfgang Ziegler Avatar answered Sep 06 '25 22:09

Wolfgang Ziegler


You stack in misunderstanding of how SetValue method behave, it takes an real object as first parameter which have the property which propertyInfo is described, so you need to take that object form expression instead of using expression itself, please take a look at the following answer on stakoverflow which may help you link to post

like image 24
Victor Avatar answered Sep 06 '25 23:09

Victor