nullable object must have a value

前端 未结 8 1734
梦如初夏
梦如初夏 2020-11-30 00:17

There is paradox in the exception description: Nullable object must have a value (?!)

This is the problem:

I have a DateTimeExtended class, tha

相关标签:
8条回答
  • 2020-11-30 00:31

    I got this solution and it is working for me

    if (myNewDT.MyDateTime == null)
    {
       myNewDT.MyDateTime = DateTime.Now();
    }
    
    0 讨论(0)
  • 2020-11-30 00:32

    You should change the line this.MyDateTime = myNewDT.MyDateTime.Value; to just this.MyDateTime = myNewDT.MyDateTime;

    The exception you were receiving was thrown in the .Value property of the Nullable DateTime, as it is required to return a DateTime (since that's what the contract for .Value states), but it can't do so because there's no DateTime to return, so it throws an exception.

    In general, it is a bad idea to blindly call .Value on a nullable type, unless you have some prior knowledge that that variable MUST contain a value (i.e. through a .HasValue check).

    EDIT

    Here's the code for DateTimeExtended that does not throw an exception:

    class DateTimeExtended
    {
        public DateTime? MyDateTime;
        public int? otherdata;
    
        public DateTimeExtended() { }
    
        public DateTimeExtended(DateTimeExtended other)
        {
            this.MyDateTime = other.MyDateTime;
            this.otherdata = other.otherdata;
        }
    }
    

    I tested it like this:

    DateTimeExtended dt1 = new DateTimeExtended();
    DateTimeExtended dt2 = new DateTimeExtended(dt1);
    

    Adding the .Value on other.MyDateTime causes an exception. Removing it gets rid of the exception. I think you're looking in the wrong place.

    0 讨论(0)
  • 2020-11-30 00:33

    I got this message when trying to access values of a null valued object.

    sName = myObj.Name;
    

    this will produce error. First you should check if object not null

    if(myObj != null)
      sName = myObj.Name;
    

    This works.

    0 讨论(0)
  • 2020-11-30 00:39

    When using LINQ extension methods (e.g. Select, Where), the lambda function might be converted to SQL that might not behave identically to your C# code. For instance, C#'s short-circuit evaluated && and || are converted to SQL's eager AND and OR. This can cause problems when you're checking for null in your lambda.

    Example:

    MyEnum? type = null;
    Entities.Table.Where(a => type == null || 
        a.type == (int)type).ToArray();  // Exception: Nullable object must have a value
    
    0 讨论(0)
  • Assign the members directly without the .Value part:

    DateTimeExtended(DateTimeExtended myNewDT)
    {
       this.MyDateTime = myNewDT.MyDateTime;
       this.otherdata = myNewDT.otherdata;
    }
    
    0 讨论(0)
  • 2020-11-30 00:41

    Looks like oldDTE.MyDateTime was null, so constructor tried to take it's Value - which threw.

    0 讨论(0)
提交回复
热议问题