Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get property name and type using lambda expression

I am trying to write a function that will pull the name of a property and the type using syntax like below:

private class SomeClass {     Public string Col1; }  PropertyMapper<Somewhere> propertyMapper = new PropertyMapper<Somewhere>(); propertyMapper.MapProperty(x => x.Col1) 

Is there any way to pass the property through to the function without any major changes to this syntax?

I would like to get the property name and the property type.

So in the example below i would want to retrieve

Name = "Col1" and Type = "System.String"

Can anyone help?

like image 779
pythonandchips Avatar asked Nov 07 '08 23:11

pythonandchips


People also ask

What does => mean in lambda?

In lambda expressions, the lambda operator => separates the input parameters on the left side from the lambda body on the right side. The following example uses the LINQ feature with method syntax to demonstrate the usage of lambda expressions: C# Copy.

What is the use of lambda expression in C#?

Lambda expressions and tuples The C# language provides built-in support for tuples. You can provide a tuple as an argument to a lambda expression, and your lambda expression can also return a tuple. In some cases, the C# compiler uses type inference to determine the types of tuple components.

What is an expression tree C#?

Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y . You can compile and run code represented by expression trees.


2 Answers

Here's enough of an example of using Expressions to get the name of a property or field to get you started:

public static MemberInfo GetMemberInfo<T, U>(Expression<Func<T, U>> expression) {     var member = expression.Body as MemberExpression;     if (member != null)         return member.Member;      throw new ArgumentException("Expression is not a member access", "expression"); } 

Calling code would look like this:

public class Program {     public string Name     {         get { return "My Program"; }     }      static void Main()     {         MemberInfo member = ReflectionUtility.GetMemberInfo((Program p) => p.Name);         Console.WriteLine(member.Name);     } } 

A word of caution, though: the simple statment of (Program p) => p.Name actually involves quite a bit of work (and can take measurable amounts of time). Consider caching the result rather than calling the method frequently.

like image 179
Jacob Carpenter Avatar answered Sep 23 '22 06:09

Jacob Carpenter


This can be easily done in C# 6. To get the name of property use nameof operator.

nameof(User.UserId) 

and to get type of property use typeof operator.

typeof(User.UserId) 
like image 33
Anand Patel Avatar answered Sep 20 '22 06:09

Anand Patel