Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot derive from value types in C#?

Tags:

c#

.net

types

I know that all value types are derived implicitly from the System.ValueType. and structs can implement interfaces, but I need to know why cannot derive from value types in C#.

like image 684
Ruben Capote Avatar asked Dec 09 '22 08:12

Ruben Capote


1 Answers

Firstly, value-types have no object header (because they aren't objects), so there would be no way to identify the actual type, or to do virtual dispatch.

Secondly - how could you add fields to sub types? The size has to be known by the compiler (for stack space etc), so:

Foo foo = ...

must always take the same amount of space.

Likewise, an abstract base-type wouldn't work, as you can always construct a struct.

Basically, they would be horrible malformed things, crippled and ugly.

I find it interesting that you would want a subtype of a value - that sounds a bit like a confused usage of a struct.

like image 167
Marc Gravell Avatar answered Dec 23 '22 10:12

Marc Gravell