Search code examples
c#reflectionfunc

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?


Solution

  • 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");