Created
July 17, 2014 05:53
-
-
Save ShawInnes/cfd515b35cdf86eaf920 to your computer and use it in GitHub Desktop.
Lambda Generic Property Setter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
Test instance = new Test(); | |
instance.Dump("Before"); | |
instance.GetSetting(p => p.Thing); | |
instance.GetSetting(p => p.AnotherThing); | |
instance.GetSetting(p => p.StringThing); | |
instance.Dump("After"); | |
} | |
// Define other methods and classes here | |
public class Test | |
{ | |
[System.ComponentModel.DefaultValue(12334)] | |
public int Thing { get; set; } | |
public int AnotherThing { get; set; } | |
[System.ComponentModel.DefaultValue("Holy Cow")] | |
public string StringThing { get; set; } | |
} | |
public static class PropertySetterExtensionMethods | |
{ | |
public static void GetSetting<T, U>(this T target, Expression<Func<T, U>> propertyExpression) | |
{ | |
var memberExpr = propertyExpression.Body as MemberExpression; | |
if (memberExpr == null) | |
throw new ArgumentException("propertyExpression should represent access to a member"); | |
// this is needed to load/save the value from storage | |
string memberName = memberExpr.Member.Name; | |
var defaultAttribute = memberExpr | |
.Member | |
.GetCustomAttributes(typeof(System.ComponentModel.DefaultValueAttribute), false) | |
.Cast<System.ComponentModel.DefaultValueAttribute>() | |
.SingleOrDefault(); | |
if (defaultAttribute == null) | |
return; | |
U defaultValue = (U)defaultAttribute.Value; | |
if (defaultValue.GetType() != typeof(U)) | |
return; | |
var property = memberExpr.Member as PropertyInfo; | |
property.SetValue(target, defaultValue, null); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment