C# – Get int value from enum

The simplest way to get an enum’s int value is by casting it to an int. Here’s an example: This outputs the following: When the enum is generic (of type ‘Enum’) You can’t cast a generic ‘Enum’ to int, otherwise you get a compiler error (CS0030 Cannot convert type ‘System.Enum’ to ‘int’). Use Convert.Int32() instead. … Read more

ASP.NET Core – How to receive a request with text/plain content

When a request comes in and your action method has parameters, the framework tries to find the appropriate InputFormatter to handle deserializing the request data. There’s no built-in text/plain InputFormatter though, so when you send a request with text/plain content, it fails with a 415 – Unsupported Media Type error response. In this article, I’ll … Read more

C# – Using reflection to get properties

You can get a list of a type’s properties using reflection, like this: Note: If you have an object, use movie.GetType().GetProperties() instead. This outputs the following: When you use GetProperties(), it returns a list of PropertyInfo objects. This gives you access the property’s definition (name, type, etc…) and allows you to get and modify its … 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

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