No compile time error happens. At runtime in the second code block, you'll get the exception that an object
really isn't a Label
and can't be cast as such.
Because every .NET type inherits from object
, you can assign any type to your object myObject;
field. In your first code block, a Label
instance is assigned to it. You can cast it back to a label as happens at (myObject as Label)
, because you actually stored a Label
in it.
Your second code example stores an object
, which isn't a Label
, so it can't be cast.