Last active
December 11, 2015 20:28
-
-
Save hagbarddenstore/4655470 to your computer and use it in GitHub Desktop.
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
using System; | |
namespace Test | |
{ | |
using System.Linq.Expressions; | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var a = new A(); | |
Console.WriteLine(a.GetPropertyName(x => x.B)); | |
Console.WriteLine(a.GetPropertyNameLocal(x => x.B)); | |
Console.WriteLine("Press Enter to exit..."); | |
Console.ReadLine(); | |
} | |
} | |
static class Extensions | |
{ | |
public static string GetPropertyName<T1, T2>(this T1 source, Expression<Func<T1, T2>> expression) | |
{ | |
var propertyExpression = expression.Body as MemberExpression; | |
var name = propertyExpression.Member.Name; | |
return name; | |
} | |
} | |
class A | |
{ | |
public A() | |
{ | |
Console.WriteLine(GetPropertyNameLocal(x => x.B)); | |
Console.WriteLine(this.GetPropertyName(x => x.B)); | |
} | |
public string B { get; set; } | |
public string GetPropertyNameLocal<T1, T2>(Expression<Func<T1, T2>> expression) | |
where T1 : A | |
{ | |
var propertyExpression = expression.Body as MemberExpression; | |
var name = propertyExpression.Member.Name; | |
return name; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment