Konrad Viltersten
Konrad Viltersten

Reputation: 39058

How to cast nullable int to nullable short?

The hits I get when I look for the answer refer to casting from short to int and from nullable to not-nullable. However, I get stuck on how to convert from a "larger" type int? to a "smaller" type short?.

The only way I can think of is writing a method like this:

private short? GetShortyOrNada(int? input)
{
  if(input == null)
    return (short?)null;
  return Convert.ToInt16(input.Value);
}

I wish to do that on a single line, though, because it's only done a single place in the entire code base for the project and won't ever be subject to change.

Upvotes: 4

Views: 7562

Answers (3)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

What's wrong with simple cast? I tested and that works fine.

private static short? GetShortyOrNada(int? input)
{
    checked//For overflow checking
    {
        return (short?) input;
    }
}

Upvotes: 13

Joël Salamin
Joël Salamin

Reputation: 3576

Is that what you're looking for?

private short? GetShortyOrNada(int? input)
{
  if(input == null)
    return (short?)null;
  if(input > Int16.MaxValue)
    return Int16.MaxValue;
  if(input < Int16.MinValue)
    return Int16.MinValue;
  return Convert.ToInt16(input.Value);
}

I just added IF clauses for the cases of too large values.

If you just want to return null if the value is not in the desired range:

private short? GetShortyOrNada(int? input)
{
  if(input == null || input < Int16.MinValue || input > Int16.MaxValue)
    return (short?)null;

  return Convert.ToInt16(input.Value);
}

Hope this will help.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You could replace a conditional statement with a conditional expression, like this:

short? res = input.HasValue ? (short?)Convert.ToInt16(input.Value) : null;

Upvotes: 2

Related Questions