Use Target Typed New Expressions to infer type on the right in C# 9 +

In C# 9 Target Typed New Expressions were introduced. They allow us to infer type on the right, whereas var allows us to infer type on left. The simple example below shows how we can omit the type when using ‘new()’ so the code becomes a little cleaner. Click on the image for a larger … Continue reading Use Target Typed New Expressions to infer type on the right in C# 9 +

Use params keyword in C# to accept a variable number of arguments of the same type

Do you know about the PARAMS keyword in C# ? The params keyword allows us to create methods that accept a variable number of arguments of the same type. The params parameter is always an array, can only be used once and it must be the last parameter in the list of parameters. Here’s a … Continue reading Use params keyword in C# to accept a variable number of arguments of the same type

String.Equals with OrdinalIgnoreCase compared to ToLower / ToUpper for string insensitive comparisons in C#

In C#, when checking if strings are equal in a case insensitive way prefer string.Equals with OrdinalIgnoreCase over using ToLower() / ToUpper(). Why? Correctness Using ToUpper or ToLower can lead to incorrect results in certain cultures and languages. Not all languages follow the simple upper-to-lowercase mapping that English does. For example, in Turkish, the lowercase … Continue reading String.Equals with OrdinalIgnoreCase compared to ToLower / ToUpper for string insensitive comparisons in C#

Use local functions in C# to encapsulate logic to a single calling method

💡 – Did you know we can use local functions in C# to scope logic only to their containing methods? For readability it can be a big help to break up large methods into smaller well-named methods. When we use private methods for this however, they are scoped privately to the class when really they … Continue reading Use local functions in C# to encapsulate logic to a single calling method

Get method caller info in C# using info attributes

C# Tip 💡 – Did you know we can get info about the caller of a method using C# (5+) info attributes? The example below shows the caller member name, file path and line number being outputted as we have annotated the parameters of the TraceMessage method with the CallerMemberName, CallerFilePath and CallerLineNumber attributes. These … Continue reading Get method caller info in C# using info attributes

C# Explicit Operator example to map from one type to another

In .NET we have plenty of ways to map objects to one another. Below is an example, courtesy of ChatGPT of using the EXPLICIT OPERATOR 👇🏻. How do you like to convert objects from one type to another? AutoMapper? Mapster? Plain left-right assignment perhaps using the Explicit Operator or Extension methods? The words are often … Continue reading C# Explicit Operator example to map from one type to another