Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy are .NET value types sealed?
    primarykey
    data
    text
    <p>It's not possible to inherit from a C# struct. It's not obvious to me why this is:</p> <ul> <li>Clearly you can't have a reference type that inherits from a value type; this wouldn't work</li> <li>It doesn't sound reasonable to inherit from one the primitive types (Int32, Double, Char, etc.)</li> <li>You'd need to be able to call (non-virtual) methods on the base using a derived instance. You could cast from a derived struct to the base, since they would overlap the same memory. I guess casting from a base to derived wouldn't work, since you couldn't know the type of the derived struct at runtime.</li> <li>I can see that you couldn't implement virtual methods in your class hierarchy, since value types can't have virtual members</li> </ul> <p>I wonder if this is a technical limitation in the CLR, or something that the C# compiler stops you from doing?</p> <p><strong>Edit:</strong> Value types can't have virtual methods, and I realise this limitation rules out most scenarios in which you'd want to use inheritance. That still leaves inheritance-as-aggregation, though. Imagine a <code>Shape</code> struct with a <code>Colour</code> field: I can write code that accepts any struct derived from <code>Shape</code>, and access its <code>Colour</code> field, even if I can never write a virtual <code>Shape.Draw</code> method.</p> <p>I can think of one scenario that would get broken by non-sealed value types. Value types are supposed to implement <code>Equals</code> and <code>GetHashCode</code> correctly; even though these two methods on <code>System.Object</code> are virtual, they get called non-virtually on value types. Even if value types weren't sealed, someone writing a struct derived from another one couldn't write their own implementation of these two methods and expect to have them called correctly.</p> <p>I should point out that I'm not suggesting I should be able to inherit from structs in my own code. What I am trying to do, though, is to guess why this particular code smell is forbidden by .NET.</p> <p><strong>Edit 2:</strong> I just spotted <a href="https://stackoverflow.com/questions/1222935/why-dont-structs-support-inheritance">this very similar question</a>, the answer to which is effectively "because then arrays of value types wouldn't work".</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload