Search code examples
c#resharperresharper-7.1

Why does ReSharper think MailMessage.From cannot be null?


[Note: This is similar to Compare string to null - Why does Resharper think this is always false?, but from the source, it appears there is no [NotNull] attribute on MailMessage.From.]

Consider this method:

public void Send(MailMessage mailMessage)
{
    if (mailMessage.From == null)
        mailMessage.From = new MailAddress(Settings.SmtpSettings.From);
    _smtpClient.Send(mailMessage);
}

ReSharper 7.1.1 is warning me that mailMessage.From cannot be null. I'm completely baffled by this.

mailMessage.From is a MailAddress which is a class (not a struct), so I would think it could definitely be null (although I concede it certainly shouldn't be at the time the message is sent).

Here is an image showing the ReSharper tooltip I'm getting:

ReSharper indicating that mailMessage.From == null is always false

Any explanation why ReSharper 7.1 thinks mailMessage.From cannot be null, or is this a bug?

Update

So the plot thickens...

I wrote a couple tests and got unexpected results.

This test fails:

[Test]
public void FromPropertyOfMailMessageCannotBeNull()
{
    var message = new MailMessage();
    Assert.IsNotNull(message.From);
}

And this one passes:

[Test]
public void FromPropertyOfMailMessageIsNullIfDefaultConstructorIsUsed()
{
    var message = new MailMessage();
    Assert.IsNull(message.From);
}

So, it looks like ReSharper is just plain wrong that MailMessage.From cannot be null.


Solution

  • It is a bug in ReSharper annotations. In .netFramework 4.0 this property has check for null value in it's setter but non-null value is not gauranted in the default constructor of MailMessage class. I've logged an issue for that: http://youtrack.jetbrains.com/issue/RSRP-337152