简体   繁体   中英

Operand Never Null Warning

I'm writing some logic which will get a start date on an object if it isn't null or it will get the min value.

var statusStartDate = ((DateTime?)previousCategory?.StartDate) ?? DateTime.MinValue;

Resharper is generating a warning that the Operand is never null:

在此处输入图片说明

If the previous category in the scenario is null, how would this not create a left hand operand being null or is this just a bug in resharper?

EDIT

Verifyable Example with DateTime

    public class Test
    {
        public Date2 startDate;

        public List<Test> testList = new List<Test>();

        public struct Date2
        {
            public static explicit operator Date2(DateTime date)
            {
                return default(Date2);
            }

            public static explicit operator DateTime(Date2 date)
            {
                return default(DateTime);
            }
        }


        public DateTime BS()
        {
            var tmp = testList.LastOrDefault();
            var testDate = ((DateTime?)tmp?.startDate) ?? DateTime.MaxValue;
            return testDate;
        }
    }

var test = new Test();
test.BS();
var x = test.BS();

If you run your test Object:

public class Test
{
    public DateTime startDate;
}

void main()
{
 var t = new test();
var time=t.startDate
}

time varible is not null and has "{1/1/0001 12:00:00 }" value it's the reason that resharper make a warning. In some situation for exmaple FirstOrDefault(x=>x...) on a list, that may have null result, you can user youe code Without any warning

在此处输入图片说明

Update:In second senario Resharper makes mistake because:

var check = ((DateTime?) tmp?.startDate).HasValue;// false , startDate is null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM