C# missing simple possible null references

  • versions used: SonarQube Enterprise 8.2.0.32929, c# plugin 8.6 (build 16497)
  • error observed: False negative, missing some simple possible null reference exceptions
  • steps to reproduce: see below class

One of our developers was tracking down some null reference exceptions our application was getting, and was surprised that SonarQube wasn’t catching them. Resharper was (though the person who wrote the code wasn’t using that). Here’s a simple class that demonstrates two of them:

using System;
using System.Collections.Generic;
using System.Linq;

namespace SonarQubeIssues {
	public class NullReferenceTest {

		public void FirstOrDefaultTest( ) {
			var list = this.GetCollection( );
			var item = list.FirstOrDefault( i => i.Id == 4 );
			item.Amount = 10m; // this will cause a null reference exception
		}

		private ICollection<TestObject> GetCollection( ) {
			var lots = new List<TestObject> {
				new TestObject { Id = 1 },
				new TestObject { Id = 2 },
				new TestObject { Id = 3 }
			};

			return lots;
		}

		public void NullableObjectTest( ) {
			var item = new TestObject( );
			var test = (byte?) ( item.Date.Value > DateTime.Now.AddDays( -365 ) ? 0 : 1 ); // this will cause a null reference exception
			Console.WriteLine( test );
		}
	}

	public class TestObject {
		public int Id { get; set; }
		public DateTime? Date { get; set; }
		public decimal? Amount { get; set; }
	}
}

Hello Brian,

The first case with FirstOrDefault is clear False-Negative. I’ve created this issue to track it.

The second one clearly leads to NullReferenceException, but we don’t track properties for rule S2259. Properties could be set/modified outside the current procedure scope (inside a constructor of partial class for example or completely outside the class) and reporting all properties would cause too many noise in that case.