views:

1287

answers:

3

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

private class SomeClass
{
    Public string Col1;
}

PropertyMapper<Somewhere> propertyMapper = new PropertyMapper<Somewhere>();
propertyMapper.MapProperty(x => x.Col1)

Is there any why to pass the property through to the function with out any major changes to this syntax.

What i would like to pull out is the property name and the property type.

so in the example bellow i would want to retrive name = "Col1" and type = "System.String"

Can anyone help.

Cheers Colin G

A: 

Cheers for the quick responce.

Had a feeling it might be a bit of a long shot will just have to rethink and come up with other syntax.

Cheers Again Colin G

Colin G
+16  A: 

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.

Jacob Carpenter
Cheer for the correct info. Have it working as I wanted now. Many THanks
Colin G
+1  A: 

Jacob's answer is absolutely right. Always remember that a lambda expression can be converted into either a delegate or an expression tree.

Jon Skeet