Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Resharper "Possible Null Reference Exception" warnings

Let's say I have an interface with a read-only property and and a concrete class where the property is instantiated in the constructor and marked as read-only.

internal interface IExample
{
    ObservableCollection<string> Items { get; }
}


internal class Example : IExample
{ 
    private readonly ObservableCollection<string> _items;

    public Example()
    {
       _items = new ObservableCollection<string>();
    }

    public ObservableCollection<string> Items
    {
       get { return _items; }
    }
}

When I use the interface Resharper warns me that I might have a possible null reference in calling code.

public class ExampleWithWarnings
{
    public void Show()
    {
       IExample example = new Example();

       // resharper warns about null reference
       example.Items.Add( "test" );
    }
}

I realize that by definition the interface doesn't guarantee that the property will have a value. (I also recognize that properties on interfaces aren't ideal). But I know this property will always have a value.

Is there any magic attribute that I can put on the interface that would prevent Resharper from showing a warning? I'd rather not have to decorate all usages of the class with a disable pragma warning.

like image 224
bryanbcook Avatar asked Mar 02 '11 19:03

bryanbcook


2 Answers

Yes, there is an attribute you can use: JetBrains.Annotations.NotNullAttribute. But you don't need to add a reference to ReSharper in your project. You can use your own implementation: open the ReSharper options, and under Code Inspection > Code Annotations you will find a "Copy default implementation to clipboard". Now just paste that into a code file in your project. You can even change the namespace.

The Code Annotations settings

And then slap the attribute in the interface property.

You should also have a look under Code Inspection > Settings and pick "Assume entity can be null... when entity is explictly marked with CanBeNull attribute, or checked for null". This way you only get warnings in the members you explicit mark as troublesome.

The Code Inspection settings

like image 196
R. Martinho Fernandes Avatar answered Oct 15 '22 06:10

R. Martinho Fernandes


You can reduce this warning to a suggestion. You could also edit the external annotation files to create custom rules or behavior: http://msmvps.com/blogs/peterritchie/archive/2008/07/21/working-with-resharper-s-external-annotation-xml-files.aspx

like image 32
KeithS Avatar answered Oct 15 '22 04:10

KeithS