Search code examples
c#lambdaextension-methodsexpressionstrong-typing

Extension method for strongly typed property access


I have the following class hierarchy

class Test
{
    public string Name { get; set; }
}

class TestChild : Test
{
    public string Surname { get; set; }
}

I can't change the Test class. I want to write following extension method like this:

static class TestExtensions
{
    public static string Property<TModel, TProperty>(this Test test, Expression<Func<TModel, TProperty>> property)
    {
        return property.ToString();
    }
}

To be able to use it in the following way:

class Program
{
    static void Main(string[] args)
    {
        TestChild t = new TestChild();
        string s = t.Property(x => x.Name);
    }
}

But now compiler says

The type arguments for method 'ConsoleApplication1.TestExtensions.Property(ConsoleApplication1.Test, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

I want to have something like mvc Html.TextBoxFor(x => x.Name) method. Is it possible to write extension to be used as shown in the Main method?


Solution

  • static class TestExtensions
    {
        public static string Property<TModel, TProperty>(this TModel test, Expression<Func<TModel, TProperty>> property)
        {
            return property.ToString();
        }
    }
    

    The compiler should be able to infer the first argument...