NotNull attributes for properties missing from object initializers

Hey!

First off, thanks for the great product ReSharper is! :)

I have a suggestion which I believe would greatly enhance the static code analysis for users who use the JetBrains.Annotations namespace to decorate their properites and fields with the NotNullAttribute where it's applicable:  ReSharper does a great job of informing you when you've set such a field or property to null, or to a variable which itself could be null, but it fails to consider an important scenario -- what if the properites of an object are set via an object initializer, and a new property is added to the object as [NotNull] -- there is no indication that the new property has not been included in all such object initializers, and such a value would be initialized as null because it's not handled.

I would suggest that if an object has one or more NotNull properties, and within scope, if the object is created and initialized via an object initializer, then any NotNull property/field that is not also included the object initializer and is not set at any other point in the same scope produce a warning.  So for example of a class defnied as:

class MyClass {
   [NotNull] string A { get; set; }
   string B { get; set; }
}

MyClass x = new MyClass {
   B = "b"
};

This would produce a warning in my proposal since A is decorated with [NotNull] but is not included in the object initializer.  Similarly:

{

   MyClass x = new MyClass {
      B = "b"
   };

   x.A = "a";
}

Would NOT produce a warning, because while the NotNull member is not included in the object initializer, it was set by a separate statement within the same scope as the first initialization, which used the object initializer.

In large projects with many data transfer objects and translator classes, as objects are enhanced with additional members as new features are spec'ed, this particular warning would help me track down all the instances I may forget to find otherwise except through failures of unit testing.

Please sign in to leave a comment.