Downcasting

G

Guest

From C# Language Specification, 7.6.6 Cast expressions:
--------------------------------------------------------------------
A cast-expression of the form (T)E, where T is a type and E is a
unary-expression, performs an explicit conversion (Section 6.2) of the value
of E to type T. If no explicit conversion exists from the type of E to T, a
compile-time error occurs.
--------------------------------------------------------------------
Object E;
....
Foo F = (Foo)E;

There is no explicit conversion from Object to Foo, but the compiler can't
throw an error - whether the conversion will work isn't known until runtime.
 
J

Joe Mayo

Hi Me,

If you look at paragraph 6.2.3, it explains that reference type conversions
require run-time checks to ensure they are correct. Since E is type object,
operation Foo F = (Foo)E; is a reference type conversion.

Joe
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top