NULL Type and ReSharper Warning

I have the following code:

private static LogLevel? _logLevel = null; public static LogLevel LogLevel { get { if (!_logLevel.HasValue) { _logLevel = readLogLevelFromFile(); } return _logLevel.Value; } } private static LogLevel readLogLevelFromFile() { ... } 

I get a ReSharper warning in the return about a possible System.InvalidOperationException , and I suggest checking _logLevel to see if it is null first. However, readLogLevelFromFile returns LogLevel , not LogLevel? so the return cannot be reached when _logLevel is null . Is this just a ReSharper oversight, or am I missing something?

+7
null c # nullable resharper
source share
3 answers

This seems like a bug in Resharper.

Please note, however, that this is not thread safe.

The best way to do this is to use a static initializer , for example:

 public static LogLevel Instance { get { return Nested.level; } } class Nested { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static Nested() { } internal static readonly LogLevel level = readLogLevelFromFile(); } 
+5
source share

You can remake it into something like this:

 return (_logLevel = _logLevel ?? readLogLevelFromFile()).Value; 

Alternatively, you can use the built-in lazy type (.NET 4.0 is required or you can flip your own.):

 public static LogLevel LogLevel { get { return _logLevel.Value; } } private static Lazy<LogLevel> _logLevel = new Lazy<LogLevel>(readLogLevelFromFile); 
+4
source share

Resharper was not β€œsmart” to figure this out for you. I would suggest that this is pretty hard to understand.

I prefer @ChaosPandion refactoring anyway ...

0
source share

All Articles