CSharp 10 Features

Last Updated: 4/20/2022

Caller Argument Expression Attribute

  • You use the System.Runtime.CompilerServices.CallerArgumentExpressionAttribute when you want to know the expression passed as an argument to a method for diagnostic purpose.

Simple Example

static void CheckExpression(bool condition, [CallerArgumentExpression("condition")] string message = null )
{
	if(condition) {
		Console.WriteLine("continue success");
	}
	else
	{
		Console.WriteLine($"Condition failed - {message}");
	}
}}

var a = 5;
CheckExpression(a > 5);
//output: Condition failed - a > 5 

Filter Example

In this example, FilterPersons takes a predicate to filter the list of the persons. If the result count is zero, the predicate expression is logged.

public record Person(int Id, string FirstName, string City);

static List<Person> persons = new List<Person>() {
	new Person(1, "Person1", "Chennai"),
	new Person(2, "Person2", "Mumbai"),
	new Person(3, "Person3", "Delhi"),
};
	
static List<Person> FilterPersons(Func<Person, bool> condition,  [CallerArgumentExpression("condition")] string message = null) {
	var result = persons.Where(condition);
	if(result.Count() == 0) {
		Console.WriteLine($"filter 0 records - {message}");
	}
	return result.ToList();
}

FilterPersons(p => p.City == "Bangalore");

//output: filter 0 records - p => p.City == "Bangalore"

Example