The following code in C# will throw an InvalidOperationException because it's not allowed to access Value when it is not set.
int? a = null;
Console.Writeline(a.Value);
I have the following code in AspNet.Core:
public class Request
{
[Range(10, 20]
public int? Field1 {get; set;}
[Range(10, 20]
public MyStruct Field2 {get; set;}
}
public struct MyStruct
{
public int Value => throw new Exception();
}
When model validation happens framework just throws an exception because it tries to read all the properties of MyStruct
and it obviously cannot read Value
. But if I have only nullable field, validation works just fine even though Value
there throws an exception as well.
Is there some magic that is just hardcoded to not do that for nullable or is there some way I can have the same behaviour in my code? I.e. I want the validation to not throw an exception for my class.
I have a suspicion is that this is either a hardcoded check or it's some syntactic sugar that makes Nullable
struct possible to assign and compare to null.