Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why System.Enum is not a value-type?

Tags:

c#

.net

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?

like image 798
smwikipedia Avatar asked Feb 24 '10 06:02

smwikipedia


People also ask

Is an enum a value type?

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 .

Why is enum value type?

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.

Is enum a value type in C#?

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.

Is enum value type or reference Swift?

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.


1 Answers

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.

like image 62
Jon Skeet Avatar answered Sep 20 '22 17:09

Jon Skeet