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
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 to share