Sunday, February 04, 2007

Why 'Value' types does not support inheritance ??

Why 'Value' types does not support inheritance ??

Few days back one of my friend has asked me this question, that time I couldn't think of any good answer that moment. Later I did some research and found that C# compiler( VB complier will do the same ) compile a structure as a "SEALED" class , which is why we can not inherit any "Structure"( read Value type ), now it raise another question why does the compiler compile it as a "SEALED" class ? is it by design ? what are the problems would happen if the compiler compile it as a normal(non-sealed in this context) class ?

After studying article of Jeffrey Ritcher, Tanj Bennett and others and discussing with my friends like Pal b and Richard and compiling my own thought with that ... here is what came out ...

It is not a limitation of C# or VB compiler, it's a limitation of .NET CLR. Though all data types (Reference-types as well as Value-types) in .NET are derived from the ultimate base class “Object”, structure in .NET has one very important advantages over class. I think that is the one of main reasons to introduce the concept of structure in .NET. And that is “Structure is lighter-weight than class”. Light-weight structure gives you better performance than class if you use it appropriately. To keep this “light-weightiness” behaviour of structure, .NET CLR considers it as a sealed class (actually all value-types are sealed class) - no object identity, no overheads for vptr (method pointer which is required to call virtual methods).

You might ask, then, how does structure support overriding methods (ToString, Equals, etc) of base class “Object”. It allows because in this case vptr will be inside “Object” class, not in structure. So, what's your take buddy ?

1 comment:

Unknown said...

Nice explannation