Created
July 27, 2018 19:49
-
-
Save rschiefer/24887b564901b205578dfbb32db95d66 to your computer and use it in GitHub Desktop.
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
void Main() | |
{ | |
var p = new Person { FirstName = "Bill", LastName= "Gates", MiddleName = string.Empty, Age = 62}; | |
Console.WriteLine(Extensions.GetName(() => p.FirstName)); | |
Console.WriteLine(Extensions.GetName(() => p.LastName)); | |
Console.WriteLine(Extensions.GetName(() => p.Age)); | |
Console.WriteLine(Extensions.GetName(() => p.Birthdate)); | |
Console.WriteLine(Extensions.GetName(() => p.Parents)); | |
Console.WriteLine(Extensions.GetName(() => p.Age.ToString())); | |
Console.WriteLine(Extensions.EnsureNotNullOrEmpty(() => p.FirstName)); | |
Console.WriteLine(Extensions.EnsureNotNullOrEmpty(() => p.LastName)); | |
Console.WriteLine(Extensions.EnsureNotNullOrEmpty(() => p.MiddleName)); | |
} | |
// Define other methods and classes here | |
public class Person | |
{ | |
public string FirstName { get; set; } | |
public string MiddleName { get; set; } | |
public string LastName { get; set; } | |
public int Age { get; set; } | |
public DateTime Birthdate { get; set; } | |
public List<Person> Parents { get; set; } | |
} | |
public static class Extensions | |
{ | |
public static string GetName<T>(this Expression<Func<T>> action) | |
{ | |
return GetNameFromMemberExpression(action.Body); | |
} | |
static string GetNameFromMemberExpression(Expression expression) { | |
if (expression is MemberExpression) { | |
return (expression as MemberExpression).Member.Name; | |
} | |
else if (expression is UnaryExpression) { | |
return GetNameFromMemberExpression((expression as UnaryExpression).Operand); | |
} | |
return "MemberNameUnknown"; | |
} | |
public static bool EnsureNotNullOrEmpty(Expression<Func<string>> member) | |
{ | |
var memberValue = member.Compile()(); | |
if (string.IsNullOrEmpty(memberValue.ToString())) | |
{ | |
throw new ArgumentException($"This property cannot be null or empty.", member.GetName()); | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment