How to pass nullable int to nullable short?

The hits I get when I search for an answer are from casting from short to int and from nullable to not-nullable. However, I am stuck on how to convert from "larger" int type? to the "smaller" type of short ?.

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

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

      

I want to do it in one line though, because it only made one place in the whole codebase for the project and will never be changed.

+3


source to share


3 answers


What's wrong with a simple app? I've tested and it works great.



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

      

+11


source


You can replace the conditional statement with a conditional expression, for example:



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

      

+1


source


Is this what you are 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 oversized cases.

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 helps.

+1


source







All Articles