Reputation: 39058
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
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
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
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