My Implementation is Better

Code on this blog can rarely be considered remotely production-worthy. Today's example could possibly take the crown as the most filthy.

First, some context. I recently was working on a project where I wanted to represent ids as custom types instead of having ints everywhere. I found a package - StonglyTypedId - which is a source generator to remove most of the boilerplate for these strongly typed ids. Andrew Lock, the package author, has a series of blog posts describing this problem he calls primitive obsession as well as how this package was designed to solve it.

In using this StronglyTypedId library with Dapper.Contrib and MySQL I came across an issue where the .NET method Convert.ChangeType is used to convert from a ulong into the generated custom PersonId type. Convert.ChangeType can not be extended for custom types and hence the bug. The solution would be to either change Dapper.Contrib to use Dappers SqlMapper type conversion system or to use the .NET TypeConverter (example below) or some other extensible conversion method.

var converter = TypeDescriptor.GetConverter(typeof(idp.PropertyType));
var newValue = converter.ConvertFrom(id);
idp.SetValue(entityToInsert, newValue, null);

However practical a solution like that may be, it wouldn't make for a good blog post. What if, being stubborn individuals, we really wanted to extend Convert.ChangeType? Is that possible? Where would such a persuit take us? The implementation is pretty limited and so I say replace it - my implementation is better!

Read more

Fun with SkipLocalsInit

The next version of C# might support the SkipLocalsInit attribute. This attribute is an indicator to Roslyn (the C# compiler) to avoid emitting the localsinit flags for the annotated methods.

This new feature can only be used with the /unsafe compiler switch - and as we shall see, with good reason.

Read more

Bonus of the Null-Propagation Operator

The Null Propagation Operator ?. has been a part of C# for almost 5 years. The feature was well-thought out and well received, and has become so prevalent in every code-base out there that I can't remember life before it.

So it was quite jarring to realise that I forgot how it works...

Read more
Page 1 of 4
Next Page »