TechQuiz Question 3: Nullable boxing

Why does Foo<int?> throw an exception?

   1:  static void Foo<T>() where T : new()
   2:  {
   3:      T t = new T();
   4:      Console.WriteLine("ToString: " + t.ToString()); 
   5:      Console.WriteLine("GetHashCode: " + t.GetHashCode()); 
   6:      Console.WriteLine("Equals: " + t.Equals(t)); 
   7:      Console.WriteLine("GetType: " + t.GetType());
   8:  }
  10:  public void Main()
  11:  {
  12:      Foo<int>();
  13:      Foo<int?>(); // Exception thrown
  14:  }


int? is a nullable type. T t = new T(); returns a Nullable<int> with a value of 
null. If we have a look at the definition of Nullable<T> we find the following:

   1:  [Serializable]
   2:  public struct Nullable<T> where T : struct
   3:  {
   4:      public Nullable(T value);
   6:      public static explicit operator T(Nullable<T> value);
   7:      public static implicit operator Nullable<T>(T value);
   9:      public bool HasValue { get; }
  10:      public T Value { get; }
  12:      public override bool Equals(object other);
  13:      public override int GetHashCode();
  14:      public T GetValueOrDefault();
  15:      public T GetValueOrDefault(T defaultValue);
  16:      public override string ToString();
  17:  }

As you can see, Nullable<T> overrides ToString, GetHashCode and Equals. Calling these methods on a nullable type is save will give you a nice result.

But GetType is another story. GetType only exists on the base class Object and cannot be overridden. When calling GetType on a Nullable<T>, your item is boxed to Object.

   1:  int i = 123;
   2:  // The following line boxes i.
   3:  object o = i;  

If you have a Nullable<T> with a value of null and you box it to object you get null 
back. Think of it like having a null value being boxed to a null reference. And calling GetType() on null gives you an exception!

Techquiz Question 2: How to test this code?

Question two in our TechQuiz is about Unit Testing.

  1. What do you think is an advantage of Unit Testing?
  2. What is the biggest problem you encounter when writing a Unit Test?
  3. If you have to test the OrderProcessor, how would you do it? How to refactor the code to make it improve testability?
public class OrderProcessor
       public void ProcessOrder(Order order)
             var creditCardService = new CreditCardService();
             creditCardService.Charge(order.Price, order.Customer.Id);
             order.IsPaid = true;


To sum it up, Unit Testing helps you with designing, developing and maintaining your code.
One of the biggest issues when using Unit Testing is not in the Unit Test itself. We can use C# for both writing our tests and the production code and we only have to learn some simple attributes and methods. But most of the time, the problem is in our production code.
Take the example of the OrderProcessor. Because the CreditCardService is constructed inside the method we can’t access it. If the service is slow running or needs an actual connection to a credit car company it will be hard to create a fast running unit test without any side effects.
But what if we change the code to the following:

public class OrderProcessorService : IOrderProcessorService
        this.creditCardService = creditCardService;
    private ICreditCardService creditCardService;
    public void ChargeOrder(Order order)
        creditCardService.Charge(order.Price, order.Customer.Id);
        order.IsPaid = true;

Now we have separated the business logic from constructing a CreditCardService. There is no hard dependency on a implementation of this service and we can easily test it by using a mock:

public void WhenTheOrderIsChargedMyCreditCardShouldBeBilled()
    // Arrange
    Customer customer = new Customer() { Id = 100 };
    Order order = new Order() { Price = 25.95M, Customer = customer };
    // Act
    ICreditCardService creditCardService =  
    creditCardService.Expect(c => c.Charge(order.Price, customer.Id));
    IOrderProcessorService orderProcessorService =
new OrderProcessorService(creditCardService);
    // Assert that my credit card is billed for the correct amount

When you are writing new code, always ask yourself how can I test this code? Separating business logic from constructing your objects will definitely improve testability.

TechQuiz Question 1 Why doesn’t my code throw an exception?

Inside VincisAqtion we’ve started with a little TechQuiz. We’re planning on  creating weekly questions to publish them on our intranet and next to the coffee machine.

The first question is: Why doesn’t the following code throw an exception?

static IEnumerable<char> CapitalLetters(string input)
    if (input == null)
        throw new ArgumentNullException(input);
    foreach (char c in input)
        yield return char.ToUpper(c);

         static void Main()

The code in this example won’t throw an Exception. This is because of the yield keyword within the foreach statement.

Yield is used to implement the ‘Iterator Pattern’. The idea behind this pattern is that you can iterate trough a collection without worrying about the underlying implementation (an array, list or a linked list or something else). Although we don’t realize it, we use this pattern daily.

Within .NET there are two interfaces that play a role in implementing the Iterator pattern: IEnumerator and IEnumerableIEnumerable  defines a method: ‘GetEnumerator()‘ that returns an instance of a class implementing  IEnumerator  for that specific collection. An Enumerator acts likes a database cursor. It points to a specific row and it can only move forward.

The following demonstrates how you can use the IEnumerable and IEnumerator:

IEnumerable<char> enumerable = CapitalLetters(“Some text”);

IEnumerator<char> enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext())
    char current = enumerator.Current;

This code shows the complete iterator pattern. The method  CapitalLetters returns an  IEnumerable . The  IEnumerable returns an  IEnumerator . The  Enumerator can loop trough a collection while holding a reference to the current element.

The code inside  CapitalLetters  is executed when you call MoveNext(). So, the exception will only be thrown when you hit  MoveNext() for the first time.

But, I’ve never ever used this code! Why should I be interested?
Probably the following code will look familair:

foreach (char current in CapitalLetters(“Some text”))

The C#  foreach statement is syntactic sugar for the iterator pattern. When the compiler finds a  foreach keyword, it will automatically expand the code to use the  IEnumerator  and call  MoveNext() and  Current.

Why does this matter for your day to day job?

First off all, this sample makes it explicit how  foreach actually works. If you want to implement a custom collection you can use  IEnumerator and IEnumerable to implement the iterator pattern so it can be used in a foreach statement

Second off all, what if the method  CapitalLetters would have some really complex logic? When would this code be executed?

Each time you hit  MoveNext()!

So when using  foreach , it’s important to realize over what type of collection you are iterating. if your collection is calculated on the fly, this could mean a huge performance hit. Especially when you execute it multiple times. Adding a ToList() mean will iterate the collection for you and store the results.

This was our first TechQuiz question. If you have any comments or maybe ideas for a new question, please share 🙂

Unit Testing, hell or heaven?

This blog is a translation of my article that’s published by the Dutch Microsoft .NET Magazine (,-hemel-of-hel)

Unit Testing is a practice of which we are all convinced that it’s a good thing. I’ve seen many teams that start out very enthusiastic with Unit Testing, but in practice it’s often disappointing.

Tests are time consuming to maintain, slow running and sometimes it’s just hard to get some code under test. For these and other reasons, Unit Testing is a practice, that when under pressure slowly fades into the background. Even when we’re on paper convinced that Unit Testing offers advantages.

In this blog I’ll discuss some errors that often cause problems and some best practices how we can tackle these.

What exactly is a Unit Test?

Many of the problems that teams encounter when using Unit Testing, arise in the definition of what exactly is a Unit Test. A Unit Test is all about testing the smallest possible piece of code to see if it meets the requirements. A Unit Test that uses a WCF service and talks to a real database is not a Unit Test.

Most of the time the Unit Test we write are not about ‘the smallest possible’. Problems such as tests that take way too much time to run, which for various indeterminable reasons just go wrong or that require constant maintenance with every code change all have to do with the failure to test the smallest possible piece of code.

We can compare this to the development of a car. You could get the whole car designed, build and then test it in its entirety. But what if the car won’t start, then what’s wrong? The battery, the motor or the wiring between them? Wouldn’t it be better to test the parts separately? Is the battery functional? If the engine gets no fuel, does it turn off? If you are confident that all  components work separately and are tested then you can be much more comfortable when you assemble the entire car. If it starts and you can drive it to the parking lot you are pretty sure everything is working.
This shows that besides the Unit Tests, you also need to test larger blocks of code or even an entire application. Then we’re talking about Functional Tests and Scenario Tests. As the picture shows, there are in a lot of Unit Tests, some Functional Tests and eventually only a small number of Scenario Test

Good Unit Tests thus provide the basis for a high quality, stable product.

But what’s so difficult about writing a Unit Test?

Writing a Unit Test is really not that difficult. Writing good testable code, however, is much more difficult and that’s where most of our problems come from.

But how can you make sure that your application can be tested as lot of small, individual parts and why does this often go wrong?

The development of an alarm clock radio

As an example, in this blog I’ll look at developing the software for a simple alarm clock that uses a service that retrieves the current time from a satellite. The hardware vendor has provided us with the following wrapper code:

public class HardwareClient

public TimeSpan DisplayTime { get; set; }
public List<TimeSpan> CurrentAlarms { get; set; }

public void StartAlarm()
{ ... }

public void StopAlarm()
{ .... }

public class SatelliteSyncService
public TimeSpan GetTime()
{ .... }

A first attempt for creating our Alarm Clock looks like the following:

public class AlarmClock
public AlarmClock()
= new SatelliteSyncService();
= new HardwareClient();

public void Execute()
= SatelliteSyncService.GetTime();

// Check for active alarms
// ....

It’s now easy to create an Alarm Clock and use it. But how would you test this code?

If we look at the definition of a Unit Test, we see that it’s about testing the smallest possible piece of code. If we now test our alarm clock, then we’re also testing the Hardware Client and the Satellite Sync Service. Is that test the smallest possible piece of code?

Suppose we want to test whether the alarm we have set really triggers. Maybe we start with creating  an alarm that’s one second into the future. In our test we have to wait until that moment passes and then we have to find out how to check with the Hardware Client if the alarm was triggered.

Mocking and Dependency Injection

It would be a lot easier if we could control all the different parts that are used by our alarm clock and test them in isolation.
What if we would replace the AlarmClock with the following:

public AlarmClock(IHardwareClient hardwareClient, ISatelliteSyncService satelliteSyncService)
= satelliteSyncService;
= hardwareClient;

There are two important changes. Instead of working with concrete classes, we work with an interface. In addition, the class now clearly states what he needs and gives us a logical seam where we can control this.

This demonstrates an important point when writing code that is easy to test:

The task of a class is to implement business logic, it’s not his job to create all kinds of objects. Look therefore whether the use of the new operator (or static data or singletons) in a class really belongs there together with business logic. Or should you move the construction logic outside the class? Make sure that you have seams in your code so you can replace a dependency in your a unit test.

In our unit test we now have the ability to replace IHardwareClient and ISatelliteSyncService with a more testable version. We can do this by creating a Mock. A Mock is an object that can be used in place of a real object and of which the behavior can be fully controlled. There are several frameworks that we can use to create Mocks. A well known mocking framework is Rhino Mocks. You can easily install it as a NuGet package.

Using Rhino Mocks we can create a new clock radio in the following manner and test it:


public void TestThatTheAlarmClockShowsTheTimeWhenExecuted()
// Arange
TimeSpan currentTime = new TimeSpan(0, 0, 1);

IHardwareClient hardwareClientMock
= MockRepository.GenerateMock<IHardwareClient>();
ISatelliteSyncService satelliteSyncServiceMock

=> h.DisplayTime).PropertyBehavior();
=> s.GetTime()).Return(currentTime);

// Act
AlarmClock clock = new AlarmClock(hardwareClientMock, satelliteSyncServiceMock);


// Assert
Assert.AreEqual(currentTime, hardwareClientMock.DisplayTime);

Of course you have to choose for each specific situation if you want to pass the dependency in the constructor or only to a specific method.

When setting a new alarm, the ISatelliteSyncService is not used . Therefore, in this case we can pass  null for the  ISatelliteSyncService . If someone else reads this test, this gives a strong message. He can be sure that if there is a problem with the code, this has nothing to do with ISatelliteSyncService.


public void TestThatWhenIAddAnAlarmItShowsUpInMyAlarmList()
// Arrange
IHardwareClient hardwareClientMock = MockRepository.GenerateMock<IHardwareClient>();
=> h.CurrentAlarms).PropertyBehavior();

// Act
AlarmClock clock = new AlarmClock(hardwareClientMock, null);
new TimeSpan(0, 0, 0));

// Assert
Assert.AreEqual(1, hardwareClientMock.CurrentAlarms.Count);
new TimeSpan(0, 0, 0), hardwareClientMock.CurrentAlarms[0]);

The Law of Demeter

Suppose you’re at the checkout and the cashier asks you for twenty euros. Would you give your wallet  to the cashier so they can get the money out or do you take the money out of your wallet and give only the twenty euro?

Probably we would all choose to give only the money. But when writing code, we make this mistake quite often. Do you sometimes pass a Customer object to a function, just to get the shipping address or a Factory which is then only used to construct something else?
Instead of having to create a complete customer with all the little details, we actually only need to pass an address.
This principle is called the Law of Demeter. Your code should only talk to his immediate friends, not against foreigners. So only pass the data that a function really needs. This in turn ensures better testable code with fewer links to other parts.

Generating test data

Another problem with writing unit tests is the test data that we need. Often this test data can be complicated to construct, which in turn makes a test very long and difficult to read.
Consider the following initialization code to test whether the price of an invoice is written to the database.

 Address billingAddress =

new Address("Stationsweg 1","Groningen", "Nederland", "9726AE");
Address shippingAddress
new Address("Aweg 1", "Groningen", "Nederland", "9726AB");
Customer customer
new Customer(99, "Piet", "Klaassens", 30, billingAddress, shippingAddress);
Product product
= new Product(88, "Table", 19.99);
Invoice invoice
= new Invoice(customer);

What exactly are the important details in this? Is it important that the shipping and billing address differ? Is it the name of the customer? In a situation like this we can of course take a pretty good guess about what’s important or we could have a look at the code to figure it out. But consider the following initialization code:

Invoice invoice = Builder<Invoice>.CreateNew()
=> i.Product = Builder<Product>.CreateNew()
=> p.Price = 19.99)

The only detail which is mentioned here is the price. All other required data is automatically filled with dummy data. Besides readability, this has another advantage. If there is any changes to the Invoic, Customer, Product, or Address class that has nothing to do with the price, we don’t have to make maintenance changes to this unit test. The Builder Pattern can save us a lot of time as a project grows.


Unit Testing is a practice with a lot of potential. As developers, however, we must remain committed to writing better testable code. Then Unit Testing will pay of and we will have the advantage that better testable code leads to better code and fewer bugs.

Welcome to my blog

Hi there, welcome to my new blog. This is a short introduction to who I am and what this blog is about.

Who am I?
My name is Wouter de Kort. I’m a developer living in the Netherlands and I’m working as a Software Architect and Technical Trainer for the .NET platform.
I’m active on Stackoverflow to keep myself up to date and I try to read as much as possible about development with a focus on architecture, .NET, unit testing and the entity framework.
So why this blog?
I’m starting this blog to share some of the things I learn during my day-to-day job for a reference for myself and others. I also want to use it to get some feedback on ideas I’m working on and I hope it will become an active place for sharing ideas.
What not?
This blog will mostly be about technical content, not about personal stuff.