Abusing IDisposable

August 27, 2019 .net c#

In C# the interface IDisposable is usually used to indicate that an object needs to dispose of unmanaged resources. C# provides the using syntax to ensure that the Dispose method is called once the instance of the object is no longer needed.

Dispose is just like any other method though and the using syntax can be used quite nicely for other use cases as well. Let's create a class we can use to collect some actions to be "deferred" until a later time.

Read More

Generating string permutations for unit testing

February 11, 2019 .net c# nunit

I needed to parse a string containing 6 characters. Each character should only be one of 3 possibilities: '?' for null, '0' for false or '1' for true. The problem sounded easy enough to generate a whole bunch of unit tests for.

Read More

Functional Card Deck in C#

October 11, 2018 c# fp

I've been inspired lately by Mark Seemann's series of posts about Applicative Functors. One of the latest posts is an example about creating a full deck of cards. Most of posts up to this point have contained a C# example but for some reason this one didn't. This inspired me to take a shot at it.

Read More

Enabling the latest version of C#

June 21, 2018 c# msbuild

As of this writing when creating a new console project via dotnet new console the version of C# used in the project is version 7.0. This means you're missing out cool features like Default Literal Expressions. The language version can be changed via Visual Studio though I prefer to enable it via MSBuild. This can be done in the csproj file or globally via a Build.Directory.props file. Changing the C# language version is done via a property known as LangVersion.

<PropertyGroup>
    <LangVersion>latest</LangVersion>
</PropertyGroup>

This property can set to any of the values listed here. As of this writing VS Code doesn't seem to like it when you use 7.3 instead of latest. VS Code will show errors in your code although the code will compile without any problems.

A neat way to curry in C#

May 25, 2018 c# fp

I was reading an older blogpost from Mike Hadlow about Partial Application in C# in which he discusses how Partial Application can be implemented in C# via Currying. Although I appreciate his example of implementing currying via extsion methods, the syntax is hideous. There is a suggestion in the comments though that I found to be a much better solution.

// Define a local function Add.
int Add(int a, int b) => a + b;

// Here we do the currying.
Func<int, int> add3 = (b) => Add(3, b);

// This will print 5.
Console.WriteLine(add3(2));

// Curry one more time so that we have
// a function that simply produces 5.
Func<int> five = () => add3(2);

// This will also print 5.
Console.WriteLine(five());