Sign in to follow this  

[.net] [C#] Casting sealed class objects to interfaces

This topic is 3577 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In Programming C#'s chapter on interfaces, Jesse Liberty writes that it's better to access interface methods through the object reference rather than through an interface reference when dealing with structs or sealed classes that implement said interfaces. He explains the case perfectly with structs. Doing the cast causes the implicit boxing, creates another instance of the struct, all the problems associated with that, etc. So, casting to an interface is bad for value types, fine. What I'm having a hard time understanding is why it's also a problem for sealed classes. I've searched high and low and can't find any explanation, and while Liberty gives an example and explanation using structs, aside from mentioning sealed classes he doesn't explain further. So, are sealed classes represented in the CLR as value types, or is there some other reason not to cast them to interface references? In Abstract and Sealed Classes and Class Members (C# Programming Guide) they mention that "some run-time optimizations can make calling sealed class members slightly faster." Are these optimizations what make casting a sealed class to an interface undesirable? What are those optimizations? I think I'll take a look at the language spec and see if there are any answers there. If not I guess I'll write some code and run it through ildasm and see if that answers my question... Also, the beginning of the interface chapter in Programming C# says an interface can define signatures/return types for "methods, properties, events, and indexers," and the chapter on interfaces in "Design Patterns in C#" says explicitly that "An interface can also contain events, but not delegates," but the help page on MSDN for the interface keyword says interfaces can declare delegate signatures. Later on in that document it doesn't mention delegates at all. Is that a typo or am I missing something?

Share this post


Link to post
Share on other sites
Sealed class method calls can be inlined. However, if you cast you object reference to an interface, inlining is no longer possible. That's the only optimization I'm aware of.

From the C# Language Spec, it does not appear that interfaces can contain delegate signatures.

Share this post


Link to post
Share on other sites
Sign in to follow this