In this article, I am going to present to you how to get property and method names from lambda expressions. You can pass properties and methods as methods’ parameters. It is particularly useful for configuration purposes. In the last example, I am going refactor a little bit my PropertiesAssert utility so that you can set the properties not to be asserted as lambda expression instead of plain text. You can read more about the PropertiesAsserter utility here: Generic Properties Validator C# Code

How to Pass Property as Lambda Expression Parameter?

First you need to write a code that enables you to pass properties as parameters. It looks a little bit scary but don’t worry.

Build Lambda Expressions ReaderThrough the type Expression<Func<T, object>> you pass the lambda expression for the property. T is the type of the class that holds the property.The next step of the process is to create a utility method to get the name of the property from the lambda expression.

You will need two methods for the job. The main method contains logic to get the name of a property, a void method or a value type method. If you pass null expression or not supported expression, an ArgumentException is thrown.

Test Drive of the NameExtensions Utility ClassIn my opinion, these methods are easier to use if they are built as extension methods. Also additionally, I added a method that accepts multiple properties’ lambda expressions. It is implemented through params operator. To pass a method as a lambda expression, use Expression<Action<T>> type for method’s parameter.

As expected on the console is displayed- FirstName, LastName, City and ToString.

Improve PropertiesAsserter Configuration by Usage of Property Lambda Expressions

In summary, the main purpose of the PropertiesAsserter is to assert all properties of an object against an expected version. However, you should be able to configure it to skip the verification of some of the properties because you may don’t know what the expected value is- such as DateTime properties, history fields and so on.In the first implementation of the utility the skip configuration of the properties not to be asserted, their names were passed as strings.

As you can assume, the later approach is error-prompt because of the possibility of typo errors and renaming of the properties.The primary method of the PropertiesAsserter can be refactored to accept params of properties’ lambda expressions. Internally it will use the new lambda expressions’ utility to get the properties names.

As you can assume, the later approach is error-prompt because of the possibility of typo errors and renaming of the properties.The primary method of the PropertiesAsserter can be refactored to accept params of properties’ lambda expressions. Internally it will use the new lambda expressions’ utility to get the properties names.