58

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?

PF_learning
  • 25
  • 13

4 Answers4

96

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

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
14

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

CodeNotFound
  • 20,646
  • 10
  • 62
  • 67
fhnaseer
  • 6,887
  • 16
  • 57
  • 106
4

suppose we have enum

public enum eCategory
{
    health ,        
    Weapon
}

and a type of eCategory such as :-

eCategory currentcategory;

then currentcategory is of value type

Eklavyaa
  • 328
  • 4
  • 15
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/

SAm
  • 2,074
  • 28
  • 28
  • I downvoted for your display of erroneous programming conventions. Enum fields should start with an uppercase letter. – Krythic Oct 19 '16 at 02:35
  • 11
    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. – mjwills Nov 16 '17 at 05:16