How to hinder reflection-based scenarios


In one easy step:  Make sure an object’s runtime type doesn’t actually match its compile-time type.  This test fails:

[Test]
public void HoorayNullables()
{
    int? i = 5;
    i.GetType().ShouldEqual(typeof(int?));
}

With a rather unexpected error message of:

Expected: <System.Nullable`1[System.Int32]>
But was:  <System.Int32>

Hmmm, that’s interesting, I wouldn’t expect an object to straight up lie to me about its type.  Even more irritating when you design a framework to examine runtime types of objects to make determinations on what to do.  This is by design, so that nullable types play as nice as possible with their underlying type counterparts.  That’s why you also see the implicit/explicit conversion operators as well.  There isn’t a way, as far as I can tell, to take an instance of an object by itself and determine if it’s a nullable type or not.

Getting stuck in the weeds