Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better method for converting int to short? (NULL if not possible)

Tags:

c#

.net

I have following two approaches for converting int to short?.

  1. First one fails if the value is not in short range.
  2. The second approach works but it has a unnecessary conversion to string.

Is there a better method?

EDIT:

From the answer below:

Int16 is just a subset of Int32 so you do not need any conversion to "intermediate" types.

CODE

//Approach 1
int vIn = 123456789;
short? vOut = Convert.ToInt16(vIn);
//Value was either too large or too small for an Int16.

//Approach 2
short? vOut2 = null;
int vIn2 = 123456789;
short number;
string characterRepresentationOfInt = vIn2.ToString();
bool result = Int16.TryParse(characterRepresentationOfInt, out number);
if (result)
{
    vOut2 = number;
}

Reference:

  1. Java: Conversion from int to short
like image 803
LCJ Avatar asked Feb 22 '13 13:02

LCJ


People also ask

How do I assign a nullable Integer to an int?

You can declare nullable types using Nullable<t> where T is a type. Nullable<int> i = null; A nullable type can represent the correct range of values for its underlying value type, plus an additional null value. For example, Nullable<int> can be assigned any value from -2147483648 to 2147483647, or a null value.

Can null be cast to Integer?

In other words, null can be cast to Integer without a problem, but a null integer object cannot be converted to a value of type int.

Can you cast an int to a long?

Java int can be converted to long in two simple ways: This is known as implicit type casting or type promotion, the compiler automatically converts smaller data types to larger data types. Using valueOf() method of the Long wrapper class in java which converts int to long.


2 Answers

Why you can't simply use the built-in conversion of the cast? Just add a check to be sure it's not out of range (if you want a null value instead of an exception).

short? ConvertToShort(int value)
{
    if (value < Int16.MinValue || value > Int16.MaxValue)
        return null;

    return (short)value;
}

About your approaches:

  1. It works (of course) but you'll never get the null value and conversion may fail if value is outside the valid range of Int16.

  2. It's terribly slow. Don't forget Int16 is just a subset of Int32 so you do not need any conversion to "intermediate" types.

like image 98
Adriano Repetti Avatar answered Sep 24 '22 01:09

Adriano Repetti


Here are a couple of possible solutions.

Static helper method:

public static class Number
{
    public static bool TryConvertToShort(int value, out short result)
    {
        bool retval = false;
        result = 0;
        if (value > Int16.MinValue && value < Int16.MaxValue)
        {
            result = Convert.ToInt16(value);
            retval = true;
        }

        return retval;
    }
}

Usage:

int a = 1234;
short b;
bool success = Number.TryConvertToShort(a, out b);

Extension method:

public static class ExtendInt32
{
    public static bool TryConvertToShort(this int value, out short result)
    {
        bool retval = false;
        result = 0;
        if (value > Int16.MinValue && value < Int16.MaxValue)
        {
            result = Convert.ToInt16(value);
            retval = true;
        }

        return retval;
    }
}

Usage:

int a = 1234;
short b;
bool success = a.TryConvertToShort(out b);

You can also create a helper/extension method that doesn't fail gracefully and instead either returns a default value (0) or throws an exception.

public static short ConvertToShort(int value)
{
    short result;
    if (value > Int16.MinValue && value < Int16.MaxValue)
    {
        result = Convert.ToInt16(value);
    }
    else
    {
        throw new OverflowException();
    }

    return result;
}
like image 30
Kevin Babcock Avatar answered Sep 25 '22 01:09

Kevin Babcock