views:

236

answers:

6

I have a data reader. I want to compare the value in it with the value 42. I know it is an integral type (e.g., what MySQL calls INT, TINYINT, SMALLINT, MEDIUMINT, BIGINT, JUMBODELUXEINT, etc.). I do not want to hardwire the actual type in to the C# code. The best I have come up with is

object x = reader.GetValue(i);
uint k = x is byte ? (byte) x
    : x is short ? (uint) (short) x
    : x is ushort ? (ushort) x
    : x is int ? (int) (int) x
    : (uint) x;
if (k == 42) { ... }

This seems incredibly long-winded. I tried using Equals but different integral types with the same value do not appear to test as equal.

Is there a better way?

+6  A: 
if(Convert.ToUInt32(reader.GetValue(i)) == 42) { ... }
Daniel LeCheminant
+7  A: 

Just checking Convert.ToUInt32(object)... yup, it works fine:

using System;

class Test
{
    static void Main()
    {
        Check((byte)10);
        Check((short)10);
        Check((ushort)10);
        Check((int)10);
        Check((uint)10);
    }

    static void Check(object o)
    {
        Console.WriteLine("Type {0} converted to UInt32: {1}",
                          o.GetType().Name, Convert.ToUInt32(o));
    }
}

In other words, your code can be:

object x = reader.GetValue(i);
uint k = Convert.ToUInt32(x);
if (k == 42) { ... }

Alternatively, given that all uints are representable as longs, if you're using a data reader could you try reader.GetInt64(i)? I don't know offhand whether the conversion will be done for you, but it's probably worth a try.

Jon Skeet
A: 

I'm not sure if i understand you correctly, but I think this should work:

int x = int.Parse(reader.GetValue(i).ToString());
if(x == 42) { // do your logic }
Galilyou
Converting something to a string and back seems a pretty ugly way of doing a simple numeric conversion, IMO.
Jon Skeet
Agreed! though I don't actually know how Convert.ToX works, but i used to think that it has to convert it to a string first.
Galilyou
A: 

You could also do Skeet's and Daniel's answers in reverse like this:

if (k == Convert.ChangeType(42, k.GetType()) { ... }

I haven't tested it though.

Mykroft
+1 just for being the freak in the room who has to do it opposite! :)
Michael Meadows
A: 

You can try this:

unit k = Convert.ToUInt32(x);

You would be better served renaming your variables, though. 1 letter variables are sooo last week.

Michael Meadows
This isn't the real code, and there would be no need to have a variable name at all if C# did not have this allergy to comparing numbers to each other... !
pdc
It's the price you pay for using a statically typed language. Neal Ford calls it "bureaucracy."
Michael Meadows
A: 

This should work:

object x = reader.GetValue(i);

uint k;
try
{
    k = Convert.ToUInt32(x);
}
catch(InvalidCastException e) { ... }
if (k == 42) { ... }
Reed Copsey