Search code examples
c#inttype-conversionnullableshort

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.


Solution

  • 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;
        }
    }