Method to accept any kind of nullable type?

B

bladethinker

Hello - I have a method that will help compare nullable booleans. It
is pasted below. I'd like to do the same for DateTime. Instead of
copying most of the code for a DateTime method, I'd like to create a
method that will accept any kind of nullable type. Yet I'm not sure
how to code the args and the rest of the code. Does anyone know how to
do that? Thanks! --bladethinker
protected virtual int CompareNullableBoolean(bool? objectX,
bool? objectY)
{
if (objectX == objectY)
{
return 0;
}

if (!objectX.HasValue && !objectY.HasValue)
{
return 0;
}

if (!objectX.HasValue)
{
return 1;
}

if (!objectY.HasValue)
{
return -1;
}

return objectX.Value.CompareTo(objectY.Value);
}puroli
 
B

Ben Voigt [C++ MVP]

Something like this?

protected virtual int CompareNullableBoolean(Nullable<S> objectX,
Nullable<S> objectY) where S : struct, IComparable<S>
 
B

bladethinker

I assume that the reason for this method existing is specifically so that 
you can treat null values as valid comparison points?

You can make the method general-purpose as so:

     int CompareNullable(object obj1, object obj2)
     {
         if (obj1 == null && obj2 == null)
         {
             return 0;
         }

         if (obj1 == null)
         {
             return 1;
         }

         if (obj2 == null)
         {
             return -1;
         }

         return Comparer.Default.Compare(obj1, obj2);
     }

Nullable<T> instances will be auto-boxed, to "null" if they are nulled,  
and to a comparable object if not.  Regular reference types of course will  
just work normally.  But it's not entirely clear from your question that  
that's an appropriate solution.  So, if the above doesn't fit your needs,  
it would be helpful if you could describe what you're doing in more  
detail, and why the above isn't suitable.

Pete

Pete, thanks for the code - it works great. I was making things too
difficult for myself.
The context of the problem is that I have custom business objects. I
wanted to be able
to sort lists of them...
List<MyObject> list...
list.Sort(new MyComparer(...))
I use the IComparer interface for generic types.
In those cases where the sort field was a generic, I thought I needed
a method explicitly for
each type (datetime?, int?, bool?, etc). But to make it easier I
tried to make one method which
would work regardless of type. I thought I had to create a signature
similar to what Ben suggested, but your solution works fine.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top