Skip to content

Instantly share code, notes, and snippets.

@johnnyreilly
Last active December 13, 2015 16:59
Show Gist options
  • Save johnnyreilly/4944545 to your computer and use it in GitHub Desktop.
Save johnnyreilly/4944545 to your computer and use it in GitHub Desktop.
Showing how to use expressions with constructors to drive strongly typed validation.
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;
}
}
public class FieldValidation
{
public FieldValidation(string fieldName, string message)
{
FieldName = fieldName;
Message = message;
}
public string FieldName { get; set; }
public string Message { get; set; }
}
//#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