I am looking for a method to pass property itself to a function. Not value of property. Function doesn\'t know in advance which property will be used for sorting. Simplest w
What I found missing from @MatthiasG's answer is how to get property value not just its name.
public static string Meth<T>(Expression<Func<T>> expression)
{
var name = ((MemberExpression)expression.Body).Member.Name;
var value = expression.Compile()();
return string.Format("{0} - {1}", name, value);
}
use:
Meth(() => YourObject.Property);
You can use an lambda expression to pass property information:
void DoSomething<T>(Expression<Func<T>> property)
{
var propertyInfo = ((MemberExpression)property.Body).Member as PropertyInfo;
if (propertyInfo == null)
{
throw new ArgumentException("The lambda expression 'property' should point to a valid Property");
}
}
Usage:
DoSomething(() => this.MyProperty);
Just to add from the answers above. You can also do a simple flag for the order direction.
public class Processor
{
public List<SortableItem> SortableItems { get; set; }
public Processor()
{
SortableItems = new List<SortableItem>();
SortableItems.Add(new SortableItem { PropA = "b" });
SortableItems.Add(new SortableItem { PropA = "a" });
SortableItems.Add(new SortableItem { PropA = "c" });
}
public void SortItems(Func<SortableItem, IComparable> keySelector, bool isAscending)
{
if(isAscending)
SortableItems = SortableItems.OrderBy(keySelector).ToList();
else
SortableItems = SortableItems.OrderByDescending(keySelector).ToList();
}
}
I would like to give a simple, easy to understand answer.
Function's parameter is this: System.Func<class, type of the property>
And we pass the Property like this: Function(x => x.Property);
Here is the code:
class HDNData
{
private int m_myInt;
public int MyInt
{
get { return m_myInt; }
}
public void ChangeHDNData()
{
if (m_myInt == 0)
m_myInt = 69;
else
m_myInt = 0;
}
}
static class HDNTest
{
private static HDNData m_data = new HDNData();
public static void ChangeHDNData()
{
m_data.ChangeHDNData();
}
public static void HDNPrint(System.Func<HDNData, int> dataProperty)
{
Console.WriteLine(dataProperty(m_data));//Print to console the dataProperty (type int) of m_data
}
}
//******Usage******
HDNTest.ChangeHDNData();
//This is what you want: Pass property itself (which is MyInt) to function as parameter in C#
HDNTest.HDNPrint(x => x.MyInt);
Why don't you use Linq for this? Like:
vehicles.OrderBy(v => v.maxSpeed).ToList();
Great solution over here...
Passing properties by reference in C#
void GetString<T>(string input, T target, Expression<Func<T, string>> outExpr)
{
if (!string.IsNullOrEmpty(input))
{
var expr = (MemberExpression) outExpr.Body;
var prop = (PropertyInfo) expr.Member;
prop.SetValue(target, input, null);
}
}
void Main()
{
var person = new Person();
GetString("test", person, x => x.Name);
Debug.Assert(person.Name == "test");
}