views:

351

answers:

1
AddOptional<tblObject>(x =>x.Title, objectToSend.SupplementaryData);

private static void AddOptional<TType>(Expression<Func<TType,string>> expr, Dictionary<string, string> dictionary)
{
    string propertyName;
    string propertyValue;

    Expression expression = (Expression)expr;
    while (expression.NodeType == ExpressionType.Lambda)
    {
        expression = ((LambdaExpression)expression).Body;
    }
}

In Above code i would like to get actual value of property title, not ony propert name , is it possible ?

+2  A: 
private static void Main(string[] args)
{
    CompileAndGetValue<tblObject>(x => x.Title, new tblObject() { Title =  "test" });
}

private static void CompileAndGetValue<TType>(
    Expression<Func<TType, string>> expr,
    TType obj)
{
    // you can still get name here

    Func<TType, string> func = expr.Compile();
    string propretyValue = func(obj);
    Console.WriteLine(propretyValue);
}

However, you must be aware that this can be quite slow. You should measure how it performs in your case.

If you don't like to pass your object:

    private static void Main(string[] args)
    {
        var yourObject = new tblObject {Title = "test"};
        CompileAndGetValue(() => yourObject.Title);
    }


    private static void CompileAndGetValue(
        Expression<Func<string>> expr)
    {
        // you can still get name here

        var func = expr.Compile();
        string propretyValue = func();
        Console.WriteLine(propretyValue);
    }
maciejkow
Hi, thanks, but it's not what i'm looking for, i would rather like to pass only expression to method and get from it name of paramether and it's value to, is it possible?
Tadeusz Wójcik
It's not possible with form you're using now. You're not passing any object, so where should code get value from? I'll try to modify your solution in a moment.
maciejkow
I've added new solution.
maciejkow