Tuesday, February 26, 2013

C# property names without hardcoded strings


public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Test
{
    protected void InitDropDownList()
    {
        DropDownList ddl = new DropDownList();
        ddl.DataSource = new List<Person> { 
            new Person{ Id = 1, Name = "John Smith" },
            new Person{ Id =  2,Name = "Moshe Perez" } };

        //Old and bad way
        ddl.DataValueField = "Id";
        ddl.DataTextField = "Name";

        //New way
        ddl.DataValueField = GetPropertyName(() => new Person().Id);
        ddl.DataValueField = GetPropertyName(() => new Person().Name);

        ddl.DataBind();
    }

    private static string GetPropertyName<T>
(Expression<Func<T>> expression)
    {
        MemberExpression body = (MemberExpression)expression.Body;
        return body.Member.Name;
    }
}



From here