Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I check a property on a generic object by passing in a lambda expression to get the parameter?

Tags:

c#

linq

Simple example, I have a Cat object with a Name property.

I have a class with a method called PrintName<T>(T objectToPrint)

I can't do Console.WriteLine(objectToPrint.Name) because it's type T.

So can I pass in the parameter as a linq expression that gets the name? Something like;

Cat c = new Cat("Bernard the Cat");

PrintName(cat, parameter: c => c.Name);

Then PrintName can just do

Console.WriteLine(cat.RunLinq(parameter));

like image 545
NibblyPig Avatar asked Dec 25 '22 23:12

NibblyPig


1 Answers

Well, you could use an Interface, but if the property can change, you could do.

First solution : if you need the property's name

PrintName<T>(T objectToPrint, Expression<Func<T, object>> property)

usage

PrintName(cat, c=> c.Name)

Then to get the "name" of the property, something like that.

var name = (property.Body as MemberExpression).Member.Name

Second solution : if you need the property's value

if you want the value of the property, use a Func<T, object> func parameter

// object if you don't know the type of the property, 
// you can limit it to string if needed, of course
PrintName<T>(T objectToPrint, Func<T, object> func)

usage

PrintName(cat, c => c.Name)

then

var value = func(cat)
like image 132
Raphaël Althaus Avatar answered Feb 15 '23 23:02

Raphaël Althaus