Last active
December 13, 2015 16:59
-
-
Save johnnyreilly/4944545 to your computer and use it in GitHub Desktop.
Showing how to use expressions with constructors to drive strongly typed validation.
This file contains hidden or 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
public class FieldValidation | |
{ | |
public FieldValidation(string fieldName, string message) | |
{ | |
FieldName = fieldName; | |
Message = message; | |
} | |
public string FieldName { get; set; } | |
public string Message { get; set; } | |
} | |
public class FieldValidation<T> : FieldValidation where T : class | |
{ | |
public FieldValidation( | |
Expression<Func<T, object>> expression, | |
string message) | |
{ | |
//Will work for reference types | |
var body = expression.Body as MemberExpression; | |
if (body == null) | |
{ | |
//Will work for value types | |
var uBody = (UnaryExpression)expression.Body; | |
body = uBody.Operand as MemberExpression; | |
} | |
if (body == null) | |
throw new ArgumentException("Invalid property expression"); | |
FieldName = body.Member.Name; | |
Message = message; | |
} | |
} |
This file contains hidden or 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
public class FieldValidation | |
{ | |
public FieldValidation(string fieldName, string message) | |
{ | |
FieldName = fieldName; | |
Message = message; | |
} | |
public string FieldName { get; set; } | |
public string Message { get; set; } | |
} |
This file contains hidden or 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
//#1 Specify field name up front - how we currently use this | |
var oldSchoolValidation = new FieldValidation( | |
"WithAProperty", "Message of some kind..."); | |
//#2 Field name driven directly by property - how we want to use this | |
var newSchoolValidation = new FieldValidation<AnObject>( | |
x => x.WithAProperty, "Message of some kind..."); | |
/// <summary> | |
/// Example class for demo | |
/// </summary> | |
public class AnObject | |
{ | |
public bool WithAProperty { get; set; } | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment