Enum is Reference Type or Value Type?
Asked Answered
I

4

65

I used Enum property in my EntityFramework 5 class, but in the database this field is nullable. Visual studio gives the error that this property must be a nullable property. My question is: is Enum a reference type or a value type?

Inquest answered 28/1, 2013 at 11:46 Comment(0)
A
104

System.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.

So if you have an enum Foo and you want a nullable property, you need the property type to be Foo?.

Arteaga answered 28/1, 2013 at 11:48 Comment(1)
Worth noting that Foo? is sugar for System.Nullable<Foo> and that Nullable is also a value type.Clupeoid
V
16

If you do myEnum.SomeValue it will be a value type.

Velarde answered 28/1, 2013 at 11:50 Comment(0)
M
5

suppose we have enum

public enum eCategory
{
    health ,        
    Weapon
}

and a type of eCategory such as :-

eCategory currentcategory;

then currentcategory is of value type

Makings answered 20/6, 2018 at 9:17 Comment(0)
Y
3
public enum TestReferenceOrValue
{
    one, two, three    
}
var a = TestReferenceOrValue.one;
var b = a;
b = TestReferenceOrValue.three;

If enums are by reference, changing b affects a
Console.Write(a); → one
Console.Write(b); → three

a great online tool for cSharp => http://csharppad.com/

Yore answered 26/6, 2016 at 18:45 Comment(2)
I downvoted for your display of erroneous programming conventions. Enum fields should start with an uppercase letter.Jeavons
The above code sample is unhelpful since it would act the same regardless of whether TestReferenceOrValue was a reference type or value type. var a = "a"; var b = a; b = "b"; Console.Write(a); Console.Write(b); shows that strings (and every type) act that way - and string is a reference type. That is because you are overwriting the b variable, not altering the object to which it points.Parvis

© 2022 - 2024 — McMap. All rights reserved.