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
Why does ReSharper think MailMessage.From cannot be null?
-
13-12-2021 - |
문제
[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:
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.
해결책
다른 팁
According to the documentation, ReSharper allows NotNullAttribute
to be applied to external APIs (such as the .NET framework itself.)
In \Program Files (x86)\JetBrains\ReSharper\v7.1\Bin\ExternalAnnotations\.NETFramework\System.Net\4.0.0.0.Nullness.Gen.xml
You have:
<member name="M:System.Net.PeerToPeer.Collaboration.PeerNearMe.AddToContactManager(System.String,System.String,System.Net.Mail.MailAddress)">
<attribute ctor="M:JetBrains.Annotations.NotNullAttribute.#ctor" />
</member>
As you can see, it's adding the NotNullAttribute
to the MailAddress
class.