Why are expression trees safer than reflection?

后端 未结 4 1578
感动是毒
感动是毒 2021-02-05 11:55

In this answer to the question of the fastest way to determine if a property contains a given attribute, user Darin Dimitrov posited that expression trees are safer than reflect

4条回答
  •  情深已故
    2021-02-05 12:38

    If we are talking about type safety and code breaking when renaming properties for example, the expression tree "advantage" is negated now that we have newer C# features like nameof():

    Expression tree way (was better before nameof()):

    Expression> expression = p => p.Id;
    var memberExpression = (MemberExpression)expression.Body;
    var property = ((PropertyInfo)memberExpression.Member);
    

    GetProperty from name (was bad before nameof()):

    var property = typeof(YourClass).GetProperty(nameof(YourClass.Id));
    

    The string input in GetProperty wasn't safe, since it was hardcoded to "Id", and when you renamed the Id property, your code would break at runtime if you didn't remember to replace this string aswell.

    That made expression trees safer, because you used the actual name of the property.

    But now that we have nameof(), the string used is actually the name of the property at compile time, and if you rename the property, and you/your IDE "forgets" to rename it in the above snippet aswell, the code will break at compile time.

    So now the old "bad way" is more concise in my opinion and probably performs minimally better aswell, since you don't need the extra casting.

提交回复
热议问题