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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With