6

I have the following code in my C# application.

DateTimeFormatInfo.CurrentInfo.DayNames

ReSharper 7.1.1 is highlighting the fact that the DateTimeFormatInfo.CurrentInfo could cause a null reference exception.

Under what circumstances would this occur? Or is this just a mistake on ReSharper's part believing that any object whose property you access should be null checked?

Dmitry Osinovskiy
  • 9,999
  • 1
  • 47
  • 38
Ryan Gates
  • 4,501
  • 6
  • 50
  • 90

1 Answers1

9

ReSharper is most probably just doing lexical analysis here and nothing deeper.

Since DateTimeFormatInfo is a class, a variable of this type can be null. Which means that the instance returned by DateTimeFormatInfo.CurrentInfo can be a null reference.

That's the error you are getting.

ReSharper doesn't understand that the method was coded such that it will not return a null reference, so it gives a warning.

Don't take the messages from ReSharper as scripture...

Pang
  • 9,564
  • 146
  • 81
  • 122
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • You make an excellent point. I wanted to make sure I understood why this was the case. – Ryan Gates Jun 04 '13 at 18:11
  • 1
    I don't know what the correct answer is, but I'm pretty sure this answer is incorrect. ReSharper is much too smart to just flag all situations where a property returns an object reference as a possible null reference error - if it did that all programs would get hundreds of these errors. As a specific counter-example I can point out that use of DateTimeFormatInfo.InvariantInfo.DayNames does not get flagged as a possible null reference error. – RenniePet May 24 '14 at 01:53
  • Someone should query JetBrains to get the correct answer. Maybe it's a bug in version 7.1. Or maybe it's possible for some strange fringe cases where the current culture info has been set to a programmer-created culture that DateTimeFormatInfo.CurrentInfo can actually return null. – RenniePet May 24 '14 at 01:55
  • 1
    It's interesting that `DateTimeFormatInfo.Current` is flagged as possibly null but `CultureInfo.CurrentCulture.DateTimeFormat` is not. – Jaanus Varus Sep 14 '16 at 16:11
  • FWIW... here's an example: 0 app 0x0169994a GetStackFrames () (vector:368) 1 app 0x0167d961 Raise (Il2CppException) (Exception.cpp:30) 2 app 0x0167da3d RaiseNullReferenceException (StringView) (Exception.cpp:61) 3 app 0x0167da31 RaiseNullReferenceException () (Exception.cpp:56) 4 app 0x00af00b1 DateTimeFormatInfo_get_CurrentInfo_m1648708929 (Il2CppObject, MethodInfo) (il2cpp-codegen.h:342) 5 app 0x00aefed9 DateTimeFormatInfo_GetInstance_m3133223810 (Il2CppObject, Il2CppObject, MethodInfo) (Bulk_mscorlib_2.cpp:8800) ... – user107172 Nov 13 '17 at 22:00