C# – How to read the Description attribute

You can use the Description attribute to describe types and type members (properties, methods). One of the most common use cases is providing a user-friendly string for enum values. Here’s an example of using the Description attribute with an enum: To read the Description attribute, use reflection and do the following steps: This can be … Read more

C# – Enum generic type constraint

Here’s how you can use Enum as a generic constraint: Note: Microsoft added this feature in C# 7.3. Whenever you have a generic method, it’s a good idea to use generic type constraints. Without constraints, you would have to implement type checking in the generic method and throw exceptions if an invalid type was used. … Read more

Error: Cannot convert null to type parameter ‘T’

Problem You’re trying to return null from a generic method and you’re getting the following compiler error: Cannot convert null to type parameter ‘T’ because it could be a non-nullable value type. Consider using ‘default(T)’ instead You can’t return null because the compiler doesn’t know if T is nullable. Solution There are a few options … Read more

C# – Use Convert.ChangeType to convert string to any type

You can use Convert.ChangeType() to convert from a string to any type, like this: Normally you’d call the specific type converter method, such as when you’re converting a string to an int. However, sometimes it makes sense to use the generalized type converter method – Convert.ChangeType() – instead of hardcoding the calls to specific type … Read more

C# – How to implement the plugin pattern

In this article, I’ll explain how to implement the plugin pattern. This approach uses a generic plugin loader that solves many real world problems when loading plugins in .NET. Besides being generic, this plugin loader also solves the following real world problems when working with plugins: If you find that this generic plugin loader doesn’t … Read more

Multithreaded quicksort in C#

One day I decided to challenge myself by trying to implement multithreaded quicksort. I wanted to see how it would compare to the built-in Array.Sort() method. I came up with two algorithms that were 2-4x faster than Array.Sort(): After continuing to tinker, in attempts to further optimize, I came across the AsParallel().OrderBy() method (PLINQ). After … Read more

C# – Using custom attributes

Attributes are used to store additional info about a class/method/property. The attributes are read at runtime and used to change the program’s behavior. Here are a few examples of commonly used built-in attributes: In general, you should try to use built-in attributes when possible. When it makes sense, you can create your own custom attribute. … Read more