johnny 5 February 2016

How to Set a property using a func<>

Say I have a function How do i set the property on the record

public void SetProperty<TRecord, TEnum>(TRecord item,  
                                        Func<TRecord, TEnum> property, string enumValue )
   where TEnum : struct
   where TRecord : class
{
     TEnum enumType;
     if (Enum.TryParse(enumValue, true, out enumType))
     {
         //How Do I set this?
         property.Invoke(item) = enumType;
     }
}

I'd prefer not to switch this to an expression. Does anybody know how to set the property?

Answers


Matthew Whited February 2016

public void SetProperty<TRecord, TEnum>(TRecord item,
                                Action<TRecord, TEnum> property, string enumValue)
    where TEnum : struct
    where TRecord : class
{
    TEnum enumType;
    if (Enum.TryParse(enumValue, true, out enumType))
    {
        property(item, enumType);
    }
}

better way...

public TEnum? AsEnum<TEnum>(string enumValue)
    where TEnum : struct
{
    TEnum enumType;
    if (Enum.TryParse(enumValue, true, out enumType))
    {
        return enumType;
    }
    return default(TEnum);
}

usage examples...

myObj.Prop = AsEnum<MyEnum>("value") ?? MyEnum.Default;
//versus 
SetPropery<MyObject, MyEnum>(myobj, (r, e) => r.Prop = e, "value");

Post Status

Asked in February 2016
Viewed 1,504 times
Voted 7
Answered 1 times

Search




Leave an answer