Guid == null should not be allowed by the compiler

前端 未结 4 1995
日久生厌
日久生厌 2020-12-05 17:02

The behaviour described below is specific to .net-3.5 only

I just ran across the most astonishing behavior in the C# compiler;

I

4条回答
  •  一个人的身影
    2020-12-05 17:46

    Actually there is a case when Guild == null will return true.

    However it is kinda hard to explain.

    In ORM mapping frameworks (openAccess for example) when you have a Guid field which will have a default value of Guid.Empty of course it is possible to have the fallowing scenario :

    • You add a new Guid field + a Property
    • You upgrade the old database schema.. in this case all values will be NULL in the database.
    • If you populate an object having this null column of type Guild of course the Object WILL get an Guid.Empty value HOWEVER if you use an LINQ query ... in the LINQ query it looks the Guid is not yet populated so you need to use == null. Maybe it is a bug but this is the way it is.

    In short (using OpenAccess but probably not only) :

    var item = GetItems().Where(i => i.SomeGuidField == null); will work and u will get items with null guid this is after an schema update. item.First().SomeGuidField will return Empty Guid

    var item = GetItems().Where(i => i.SomeGuidField == Guid.Empty); will not work even if after the population of the item it will be Guid.Empty and will return empty result.

提交回复
热议问题