I write the following code for some test, and the output is out of my expectation.
public enum Days { Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday, Friday };
Console.WriteLine(typeof(System.Enum).IsValueType.ToString()); // False
Console.WriteLine(typeof(Days).IsValueType.ToString()); // True
So I check with Reflector the implementation of the Type.IsValueType property. Which is:
public bool get_IsValueType()
{
return this.IsValueTypeImpl();
}
protected virtual bool IsValueTypeImpl()
{
Type type = this;
return (((type != valueType) && (type != enumType)) && this.IsSubclassOf(valueType));
}
In MSDN, System.Enum is defined as:
[SerializableAttribute]
[ComVisibleAttribute(true)]
public abstract class Enum : ValueType, IComparable,
IFormattable, IConvertible
Then why the IsValueType implentmented that way? Why is there a detection for enumType?
An enum type is a distinct value type (§8.3) that declares a set of named constants. declares an enum type named Color with members Red , Green , and Blue .
Enum is a reference type, but any specific enum type is a value type. In the same way, System. ValueType is a reference type, but all types inheriting from it (other than System. Enum ) are value types.
Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values to integral constants, that make a program easy to read and maintain.
The Swift language provide different ways of storing data using structs, enums or classes. Classes are reference types whereas structs and enums are value types.
All enums inherit from System.Enum
. You can't inherit from a value type, therefore System.Enum can't be a value type.
It's just like System.ValueType
isn't a value type. It's just a slight oddity which comes out of the rest of the rules. To give a more concrete example of the problems which it would cause, take this code:
enum Foo : int { X }
enum Bar : long { Y }
...
Enum x = Foo.X;
x = Bar.Y;
How much space should be reserved on the stack for x
? Should it be 0 bytes, as System.Enum
itself doesn't have any fields (thus truncating data on assignment)? Should it be 8 bytes to allow for the largest possible enum type? Value type inheritance basically leads to issues around expectations, which is why it's prohibited (I believe). Those reasons apply to enums as much as to other types.
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