I created the following property, which threw an InvalidCastException
if the getter was accessed when ViewState[TOTAL_RECORD_COUNT]
was null
.
public long TotalRecordCount
{
get { return (long)(ViewState[TOTAL_RECORD_COUNT] ?? -1); }
set { ViewState[TOTAL_RECORD_COUNT] = value; }
}
My thought is that it incorrectly attempted to unbox the object in ViewState[TOTAL_RECORD_COUNT]
to an int
, which failed because it contained a long
, but I think there might be a flaw in that logic. I will leave it as an exercise to the reader to point out that flaw.
I have since changed that property to read
public long TotalRecordCount
{
get { return (long?)ViewState[TOTAL_RECORD_COUNT] ?? -1; }
set { ViewState[TOTAL_RECORD_COUNT] = value; }
}
which works just swell. Still, I am left wondering what was wrong with my original version... StackOverflow to the rescue?
Note that if i try to execute (long)(ViewState[TOTAL_RECORD_COUNT] ?? -1)
in the Immediate Window, I get the error message Cannot unbox 'ViewState[TOTAL_RECORD_COUNT] ?? -1' as a 'long'
and if I execute (ViewState[TOTAL_RECORD_COUNT] ?? -1).GetType().Name
I get Int32
. I can execute (long)-1
and end up with -1 as an Int64
...so what's up?