Ninja Nichols

The discipline of programming

Unit Testable System.IO (C#)

It seems the hardest part of writing good unit tests is trying to mock out third-party dependencies.

A surprising number of the core Microsoft libraries like System.IO simply aren’t unit testable, so I was almost unreasonably happy when I stumbled upon System.IO.Abstractions, which describes itself as “Just like System.Web.Abstractions, but for System.IO. Yay for testable IO access!”.

From their documentation:

At the core of the library is IFileSystem and FileSystem. Instead of calling methods like File.ReadAllText directly, use IFileSystem.File.ReadAllText. We have exactly the same API, except that ours is injectable and testable.

Looks like it’s being actively maintained. Just use NuGet to add it your project:

PM> Install-Package System.IO.Abstractions

BigInteger in C#

As an introduction to the world of parallel computation, my professor gave an assignment in which we were asked to write a program to find all the prime numbers between 1 and some arbitrarily large value. The restriction is that the program must have 10 threads and the work must be shared equally between the threads.

The first step however was to figure out how to represent arbitrarily large integers in C#. A unsigned long just isn’t going to cut it. I looked around and found that .NET 4.0 adds a BigInteger class in the System.Numerics namespace.

Being new to Visual Studio and C#, I was a little confused as to why a little red squiggle was appearing under “Numerics” in the line:

First I made sure that the target platform was set to “.NET Framework 4.0” by going to the Project menu, selecting “ Properties…” and double checking the Target dropdown box. That wasn’t the issue since the correct version was already selected.

Turns out I needed to manually add an assembler reference to System.Numerics.dll. The process is pretty easy. On the Project Explorer pane, right-click “References”. Click “Add Reference” and select “System.Numerics” from the “.NET” tab.

Success! The red squiggle went away.