Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a generic property as a parameter to a function?

Tags:

c#

generics

I need to write a function that receives a property as a parameter and execute its getter.

If I needed to pass a function/delegate I would have used:

delegate RET FunctionDelegate<T, RET>(T t);

void func<T, RET>(FunctionDelegate function, T param, ...)
{
    ...
    return function.Invoke(param);
}

Is there a similar way to define a property so that I could invoke it's getter and/or setter in the function code?

like image 997
Dror Helper Avatar asked Sep 21 '08 08:09

Dror Helper


1 Answers

You can also write something like:

static void Method<T, U>(this T obj, Expression<Func<T, U>> property)
        {
            var memberExpression = property.Body as MemberExpression;
            //getter
            U code = (U)obj.GetType().GetProperty(memberExpression.Member.Name).GetValue(obj, null);
            //setter
            obj.GetType().GetProperty(memberExpression.Member.Name).SetValue(obj, code, null);
        }

and example of invocation:

DbComputerSet cs = new DbComputerSet();
cs.Method<DbComputerSet, string>(set => set.Code);
like image 114
Bartosz Pierzchlewicz Avatar answered Sep 21 '22 22:09

Bartosz Pierzchlewicz