Welcome to Pete Brown's 10rem.net

First time here? If you are a developer or are interested in Microsoft tools and technology, please consider subscribing to the latest posts.

You may also be interested in my blog archives, the articles section, or some of my lab projects such as the C64 emulator written in Silverlight.

(hide this)

More on Comparing Nullable Types and Generics

Pete Brown - 09 September 2005

If you recall from yesterday's blog entry, I was having some problems trying to find a way to compare some generics which may contain nullable types. My thanks go to Dinesh and his colleagues for solving this problem for me.

Here's the new code; it's much simpler than the old code.

  protected void SetProperty<T>(ref T currentPropertyValue, T newValue)
  {
   Comparer<T> comparer = System.Collections.Generic.Comparer<T>.Default;

   if (comparer.Compare(currentPropertyValue, newValue) != 0)
   {
    currentPropertyValue = newValue;
    MarkDirty();
   }
  }

Simple! Thanks again, Dinesh!

Now, the question of figuring out how to tell if a generic is nullable becomes just an academic pursuit, rather than a critical problem. I'm still interested in a solution to that, so if you have one, please feel free to comment.

[ As an aside, Dinesh also pointed out that anonymous users could not post comments to my blog. That is now fixed. ]

Update: Dinesh had this to say:

I am glad I could be of some help and thanks again from trying the CTP. Here is how you can check for a Nullable type – it is a bit more complex but actually cleaner than using INullableValue as a "marker" interface.

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}

I will add this to my blog for broader distribution.

Thanks.


Dinesh Kulkarni


Program Manager, Visual C#

Thanks again Dinesh! I owe you a drink or something at the PDC next week :)

 
posted by Pete Brown on Friday, September 9, 2005
filed under:  

Comment on this Post

Remember me