So I use the following utility to get the name of a field/property from an instance of a class...
public static string FieldName<T>(Expression<Func<T>> Source)
{
return ((MemberExpression)Source.Body).Member.Name;
}
This allows me to do the following:
public class CoolCat
{
public string KaratePower;
}
public class Program
{
public static Main()
{
public CoolCat Jimmy = new CoolCat();
string JimmysKaratePowerField = FieldName(() => Jimmy.KaratePower);
}
}
This is great for serialization and other times when I need a string representation of the field name.
But now, I want to be able to get the field name WITHOUT having an instance of the class - for instance, if I am setting up a table and want to dynamically link the FieldNames of the columns to actual fields in a class (so refactorings, etc. will not break it).
Basically, I feel like I just don't quite get the syntax of how to accomplish this, but I imagine that it will look something like this:
public static string ClassFieldName<T>(Func<T> PropertyFunction)
{
// Do something to get the field name? I'm not sure whether 'Func' is the right thing here - but I would imagine that it is something where I could pass in a lambda type expression or something of the sort?
}
public class Program
{
public static Main()
{
string CatsPowerFieldName = ClassFieldName<CoolCat>((x) => x.KaratePower);
// This 'CatsPowerFieldName' would be set to "KaratePower".
}
}
I hope that makes sense - I'm not very good with the vocab around this subject so I know that the question is a little vague.