1

The compiler appears to show an error when using a struct/ enum or any other value type as my MVC Model.

CS0037 Cannot convert null to 'MyEnum' because it is a non-nullable value type

I created a new MVC project (in VS 2019), created an enum

public enum MyEnum
{
    One,
    Two,
    Three
}

and put it as model in the "About" view:

enter image description here

Why is that occurring?

mjwills
  • 23,389
  • 6
  • 40
  • 63
serge
  • 13,940
  • 35
  • 121
  • 205

2 Answers2

7

The compiler appears to show a error when using a struct / value type as my MVC Model.

As per this link, the model can definitely be either a class or a struct. There are pros and cons, but both are allowed.

So, why are you seeing this error then? The short answer is - this is not a real error. It is a fake error.

Visual Studio sometimes shows fake errors, particularly when the dropdown in Error List is set to Build + Intellisense (rather than Build Only).

My suggestion to you is to switch the dropdown to be Build Only. In my projects, Intellisense gives a number of fake errors hence why I leave it in Build Only mode most of the time.

It occurs in Visual Studio 2017 and 2019. I have not tested it elsewhere.

mjwills
  • 23,389
  • 6
  • 40
  • 63
  • 1
    Can confirm it happens in VS 2022, which sent me on a google-spree, and found your answer. +1 – Jamie M Aug 03 '22 at 17:53
1

I had a similar problem passing a decimal model to a view. I suffixed the decimal type with the nullable '?' operator:

@model decimal?
Gammerz
  • 73
  • 1
  • 7