C# – How to implement GetHashCode() and Equals()

The simplest way to implement GetHashCode() is to use the built-in System.HashCode.Combine() method and pick the properties you want to include. Let it do the work for you. Furthermore, the simplest way to implement Equals() is to use the is operator and compare all the properties. Here’s an example: Note: Use (Title, Year).GetHashCode() in versions … Read more

C# – Use yield return to minimize memory usage

Let’s say you want to search for specific characters in a large text file and return a list of context objects to the calling code for further processing (such as showing the results in the UI). One way to do that is to build the entire list at once and return it. If you don’t … Read more

C# – Using the is operator

You can use the is operator to check if an object is a certain type. Here’s an example: You can also use the is operator to declare a variable of the target type, like this: Note: The employee object is only available in the if block, but IntelliSense shows it out of its scope. If … Read more

C# – The nameof() operator

The nameof() operator outputs the name of the class/method/property/type passed into it. Here’s an example: Note: nameof() was added in C# 6. nameof() eliminates duplication The DRY principle – Don’t Repeat Yourself – warns us against having duplication in the code. Whenever information or code is duplicated, it’s possible to change something in one spot … Read more

C# – Using the ‘not’, ‘and’, ‘or’ operators

I’ll show examples of using the pattern matching operators – ‘not’, ‘and’, ‘or‘ – with the is operator. These are nice syntax sugar that make conditional logic a bit easier to read. Note: ‘not’, ‘and’, ‘or’ were added in C# 9. ‘not’ operator Here’s an example of the not operator: This is checking if the … Read more