Why converting int from SqlDataReader to long results in InvalidCastException?

I get an Invalid Cast Exception on the following line:

DestMinSeq = (long)rdr["MinSeq"];

When I change the query to cast MinSeq to BIGINT instead of INT, it works.

Question: why should it be illegal to cast a short to a long?

Environment:

VS 2012 SSIS project script task. 
ADO.NET connection manager. 
SQL Server 2012.
Jon Skeet
people
quotationmark

Question: why should it be illegal to cast a short to a long?

You're trying to cast a boxed short to a long. You can see this without a database:

int x = 10;
object o = x;
long y = (long) o; // Bang!

If you cast to the right type when unboxing, then cast to the type you really want, it's fine:

DestMinSeq = (long)(int)rdr["MinSeq]";

(I suspect you want int rather than short, but you'll have to check.)

people

See more on this question at Stackoverflow