When I trying to define a class which inherits from System.ValueType
or System.Enum
class, I'm getting an error:
Cannot derive from special class System.ValueType
I understand that error but what I couldn't understand is what makes ValueType
class special? I mean there is no keyword (like sealed
) or attribute to specify that this class can not be inherited.ValueType
has two attributes, Serializable
and ComVisible
but none of them is relevant with that case.The documentation says:
Although ValueType is the implicit base class for value types, you cannot create a class that inherits from ValueType directly. Instead, individual compilers provide a language keyword or construct (such as struct in C# and Structure…End Structure in Visual Basic) to support the creation of value types.
But it doesn't answer my question.So my question is how the compiler is informed in this case? Does the compiler directly check whether the class is ValueType
or Enum
when I try to create a class that inherit from a class?
Edit: Also all structs implicitly
inherit from ValueType
, but Enum
class Explicitly inherit from ValueType
,so how is that working? How the compiler figure out this situation, all of this are hard coded by compiler?
I understand that error but what I couldn't understand is what makes ValueType class special?
The class is documented as being special. That's what makes it special.
how the compiler is informed in this case?
The compiler writers read the documentation before they write the compiler.
Does the compiler directly check whether the class is ValueType or Enum when I try to create a class that inherit from a class?
Yes.
Also all structs implicitly inherit from ValueType, but Enum class Explicitly inherit from ValueType, so how is that working?
It's working pretty well.
Are all of these special cases hard coded into the compiler?
Yes.
Isn't it more appropriate to create an attribute to specify that this class is special and cannot be inherited instead of hard coding?
No, it's not. That would imply that a third party could also make a special type that needed special handling by the compiler when inherited from. How would the third party then modify the compiler to implement those rules?
Microsoft does not publish its C# compiler source code, so we can only guess the check is embedded at compiler level.
Mono's C# compiler performs this kind of check at compile time, which you can see around line 2790 in Class.ResolveBaseTypes
method,
https://github.com/mono/mono/blob/master/mcs/mcs/class.cs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With