Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 450
Konrad Viltersten Avatar asked Dec 07 '22 00:12

Konrad Viltersten


1 Answers

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;
    }
}
like image 169
Sriram Sakthivel Avatar answered Dec 08 '22 14:12

Sriram Sakthivel