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?
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With