Please take a look at the piece of code, resulting in an error:
if(obj is sortDateTime)
sortDateTime sDT = (sortDateTime) obj; //here ERROR
return m_stDate.CompareTo(sDT.m_stDate);
What you are saying is this:
if the object is of type 'sortDateTime'
Allocate memory for variable 'sDT'
Cast 'obj' to type 'sortDateTime'
Store the result in variable 'sDT'
And then you are leaving the scope – the variable is not needed anymore (it’s allocated on the ‘Stack’ and get’s released). This does not make sense. It’s an operation, that get’s executed for nothing. What you want to do is the following:
// Variable for remembering the "cast result" after the cast
sortDateTime sDT = null;
if (obj is sortDateTime)
sDT = (sortDateTime)obj; // Cast the object.
else
return 0; // "obj" is not an "sortDateTime", so we can't compare.
// Return the comparison result, if we can compare.
return m_stDate.CompareTo(sDT.m_stDate);
The compiler notices that you cannot do such an operation and throws you an error. However this would compile:
if (obj is sortDateTime)
{
sortDateTime sDT = (sortDateTime)obj;
}
but it would not make sense either, and lead to an compiler error at
m_stDate.CompareTo(sDT.m_stDate); // sDT is not a variable in scope.
This is how I would implement the method:
sortDateTime sDT = obj as sortDateTime; // 'as' leads to an casted object, or null if it could not cast
if (sDT == null)
throw new NotSupportedException("The object is not an sortDateTime");
else
return m_stDate.CompareTo(sDT.m_stDate);
Cheers!
solved Embedded statement error [duplicate]