This object is an integral type. Can I get its value in fewer than five lines of code?

StackOverflow https://stackoverflow.com/questions/631994

  •  08-07-2019
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

if(Convert.ToUInt32(reader.GetValue(i)) == 42) { ... }

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.

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 }

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.

This should work:

object x = reader.GetValue(i);

uint k;
try
{
    k = Convert.ToUInt32(x);
}
catch(InvalidCastException e) { ... }
if (k == 42) { ... }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top