Skip to content

Instantly share code, notes, and snippets.

@hagbarddenstore
Last active December 11, 2015 20:28
Show Gist options
  • Save hagbarddenstore/4655470 to your computer and use it in GitHub Desktop.
Save hagbarddenstore/4655470 to your computer and use it in GitHub Desktop.
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