Posts
49
Comments
83
Trackbacks
0
July 2009 Entries
Comparing Nullable Values

Recently we have to create methods that will manually compare 2 objects and see if they are equal – essentially check if all their properties / fields are equal.  Some of the fields are Nullable Types, which have been available since .NET 2.0 (VS2005).  It is a nice construct to have, especially to represent database fields that can also be null – this makes coding simpler because a nullable type can also contain null as a valid value.  Interestingly, talking some some people that have done .NET for awhile, very few actually ever uses it.  It’s pretty nifty actually.

For typical primitive types, we just call the Equals method – as an added bonus, most primitive types implement IEquatable<T> which means it won’t do boxing/unboxing for value types.  So when we get to these nullable types, of course there’s some wonder as to whether the Equals method will work or not.  Well, first off, there’s actually some wonderment if the code will actually crash or not.  Consider the following code:

Nullable<int> first = 5;
Nullable<int> second = 7;
bool b = first.Equals(second);

Now, the above code looks fairly benign, the code creates 2 Nullable integers and then compare the values.  Nullable Types constructs are not special – it is implemented using generics, using the Nullable<T> construct.  What happens is that in C#, there’s a shortcut to create these nullable types; the above code can also be written as follows:

int? first = 5;
int? second = 7;
bool b = first.Equals(second);

Other than the declaration, nothing is different.  It’s essentially just shorthand for C# (same shorthand for VB.NET as well) – however some developers are so used to this construct that they may have forgotten that behind the scenes it is translated as creating an instance of the Nullable<T> construct and may actually consider these declarations as native types themselves.  As such, the following code looks a bit… concerning:

int? first = null;
int? second = 7;
bool b = first.Equals(second);

At a glance, it looks like it’s a guaranteed crash – first is assigned to null, so it definitely will crash when you try to access its instance method, right?  But the above code actually works – it will return false & assign it to b.  But how?  Well, that’s because the declaration int? is just a shorthand for Nullable<int> and Nullable<T> is a value-type.  A value type cannot be null – it’ll always have an instance to it.  As such, calling the instance method doesn’t crash the program.  With nullable types, regardless of the value of the first or second variable being compared, the call to the Equals method will always be successful.

However, the Equals method that is called accepts an object as its first parameter – which meant that there will be boxing/unboxing of the values as they’re being passed into the method.  I’m actually surprised that there is no overload within the Nullable<T> construct itself that will compare against another Nullable<T> instance.  .NET provides this through the Nullable class, but it just seems weird that they didn’t implement it inside the object model itself.  So, with the advent of Extension Methods in .NET 3.0, we try to make this to be friendlier.

public static class NullableExtensionMethods
{
   public static bool IsEqualTo<T>(this Nullable<T> first, Nullable<T> second)
      where T : struct, IEquatable<T>
   {
      // if one is null, the other is not, then obviously it's not equal
      if (first.HasValue != second.HasValue) 
         return false;

      // Both either null or not null - if one is null, then they're equal
      if (first.HasValue == false)
         return true;

      // Compare by calling the IEquatable implementation
      return first.Value.Equals(second);
   }

   public static bool IsEqualTo<T>(this Nullable<T> first, T second)
      where T : struct, IEquatable<T>
   {
      // If first is null, then obviously not equal
      return first.HasValue ? first.Value.Equals(second) : false;
   }
}

The preceeding code will basically allow any nullable types variables to call the IsEqualTo method and compare it against the supplied parameter, assuming they’re the same type.  The biggest drawback to these extension methods is that they have to be named differently; per the method invocation on extension methods, the instance method implementation will always be called first as long as the parameter supplied fulfills the instance method signature.  And since the parameter of the Equals method is an object, that particular implementation will always be the one that gets called – thus the extension methods have to use a different name.

On a microscopic level, this implementation is also faster – about 2.5 times faster.  But we’re at the splitting microseconds here – on my test PC, which is not very powerful, the instance implementation takes about 2-3 microseconds each, while the above extension method implementation is about a microsecond.  We’re still talking about 1 second can call millions of times to these methods, but it was interesting to note that boxing/unboxing have a measurable cost compared to extension methods.

posted @ Friday, July 31, 2009 5:59 AM | Feedback (0)
Base class for Singleton Pattern with Generics

The singleton pattern is pretty well known – the idea is to create a single instance of an object, and only use that particular instance forever.  The construct should disallow creation of additional objects, preferably through some language construct, rather than through using manually checking, or initializing a flag.  A typical example would be like the following:

public class MySingleton
{
   private MySingleton()
   {
   }

   private static MySingleton _instance = new MySingleton();
   public static MySingleton Instance
   {
      get { return _instance; }
   }
}

By using a private (or protected constructor, depending on what you prefer / want to do with the class), it somewhat  guarantees that no outside code can instantiate the class.  The framework will automatically instantiate the _instance field, and any reference from the outside has to use the public Instance property.  If you’re paranoid about people using Reflection to instantiate this class, then you can also put some code in the constructor to check – but if they can use reflection to begin with, any flag/value you want to check can be reset anyway, so it’s a moot point.

In my current project, we have quite a bit of Singleton classes – of course there’s the debate as to whether you’re better off using a Singleton pattern, or just use static classes.  I have my own views as to when/where you should use which construct, but that’s for another post.  And as simple as it is to make a class to be a Singleton, it irks me that I have to repeatedly type that _instance field / Instance property for all my singleton classes.  So I tried to see if I can create a base class for classes that needs to be a Singleton.  This is the code result that I ended up with:

public abstract class Singleton<T>
   where T : Singleton<T>
{
   protected Singleton()
   {
   }

   private static T _instance;
   public static T Instance
   {
      get { return _instance; }
   }

   static Singleton()
   {
      _instance = (T)Activator.CreateInstance(typeof(T), true);
   }
}

The first big problem is of course, the Instance property has to return the specific type – otherwise it won’t work.  So, we have to use generics; the generic constraint used in the code above is what is termed a Recursive Generics.  The link I provide here is the first returned result from Google search for it.  The first time I heard & saw this was from a presentation by Rockford Lhotka on his CSLA framework, way back in 2005 – I thought it was pretty mind-blowing that you can actually do this.  Anyway; the generic constraint basically only allows T to be classes that derive from this class itself.  From here on, creating my Singleton class is pretty automatic:

public class MySingleton : Singleton<MySingleton>
{
   private MySingleton()
   {
   }

   public void SomeMethod()
   {
      // Do stuff here
   }
}

The class declaration looks a tad weird (again because of the recursive generics), but essentially it specifies that MySingleton class derives from Singleton<T> class, and the generic type is the MySingleton class itself.  In the base class, T is now MySingleton and the static constructor will automatically fill the _instance field before any methods/fields/properties can be accessed from the MySingleton class; it uses the Activator class to create an instance of T, and it uses the CreateInstance overload that allows using private or protected constructor.

The Singleton class still need to declare either a private or a protected constructor – If there are no constructors, .NET will automatically assume the class has a public parameterless constructor, which means the class can be instantiated by any outside code.  Calling the method does not differ from regular implementation:

private void Test()
{
   MySingleton.Instance.SomeMethod();
}

MySingleton class inherits the static Instance property from the base Singleton<T> class; and since that property returns MySingleton, then all instance methods/properties are available to consume.  Hope this can be of use…

posted @ Friday, July 24, 2009 8:11 AM | Feedback (0)
Measure more accurately with Stopwatch

I’m finding that writing blogs actually take quite a bit of time; so I’m writing this fairly short blog in Live Writer, with the hope that I can be more productive since the tool will make it easier for me to blog.  So, we’ll see :).

I’ve used the Stopwatch class for as long as I can remember.  I don’t even remember whether I get to know the class from just browsing MSDN, or reading it from another blog, or just playing around typing stuff (and looking at what’s available through Intellisense).  Whenever I have some part of the code where I’d like to time, I’ve always used it.  So, it has been very natural for me to use.

It is surprising to me that every now and then, when I asked someone to time some new method that they create to replace an old method, they see it as a very time consuming process (pardon the pun).  Using the Stopwatch class is very, very easy!  You create it, start it, and stop it (optional), and then report the time that has elapsed.

Stopwatch sw = new Stopwatch();
sw.Start();

CallSomeMethodToTime();

sw.Stop();
MessageBox.Show(sw.ElapsedMilliseconds.ToString());

Quite easy, really, as shown in the code snippet above, which shows the elapsed milliseconds for the method.  There’s even a way to create a Stopwatch that starts automatically – using the StartNew method.

Ah, but what if the time to measure is even smaller?  The snippet above uses the ElapsedMilliseconds property, which is nice, but what if the method takes less than a millisecond?  On a recent task I had to do, we have a method that is recursively called – the method execution itself is very fast (less than 1 millisecond), but higher up the stack the calling methods shows slower and slower time measurement.  It’s just a matter of the method gets called a LOT, so we would like to optimize the method, but we need a way to measure the method time which goes very fast.

This is where the ElapsedTicks property comes in.  The ElapsedTicks property gets the elapsed time, in ticks.  What’s good about this is that ticks have a high resolution – it is actually dependent on the computer itself.  If the computer (CPU actually) has a high resolution timer, it’ll use that.  As such, the resolution of this ‘Tick’ varies among computers.  This resolution is retrieved through the Frequency static property of the Stopwatch class – the value returned by Frequency denotes how many ticks are there in a second for that particular computer.

I have a fairly old Pentium 4 machine, and on my machine, Stopwatch.Frequency returns 3192160000 – so 1 second is denoted as 3,192,160,000 ticks, that’s a resolution of over 1 ns.  But, we’re not here to compare numbers – we’d like to know if we can measure things more accurately.  To show how many seconds have elapsed, we just need to divide ElapsedTicks with the Frequency value.

To ease the retrieval of these values, on my Helper project, I’ve added 2 extension methods, as follows:

public static class ExtensionMethods
{
   public static double ElapsedMilliseconds(this Stopwatch stopwatch)
   {
      if (stopwatch == null)
         throw new ArgumentException("Stopwatch passed cannot be null!");

      return 1000 * stopwatch.ElapsedTicks / (double)Stopwatch.Frequency;
   }

   public static double ElapsedMicroseconds(this Stopwatch stopwatch)
   {
      if (stopwatch == null)
         throw new ArgumentException("Stopwatch passed cannot be null!");

      return 1e6 * stopwatch.ElapsedTicks / (double)Stopwatch.Frequency;
   }
}

Having these extension methods, allow me to do the following code:

 

Stopwatch sw = new Stopwatch();
sw.Start();

SomeSlowMethod();

MessageBox.Show(sw.ElapsedMilliseconds().ToString("0.000 ms"));

sw.Reset();
sw.Start();

SomeFastMethod();

MessageBox.Show(sw.ElapsedMicroseconds().ToString("0.000 us"));

Looks almost like a property, but results in a method call instead.  And I can log / show time measurements to the microseconds.  For my current needs, this is pretty fast & accurate – on my P4 machine, setting a field took 0.8 microseconds, so even fast method calls will be in the tens or hundreds of microseconds.

I hope this helps others that would like to do some timings of their own.

posted @ Tuesday, July 14, 2009 12:08 PM | Feedback (0)
News