Annotate System.Net.Mail for nullable reference types (#33826)
authorStephen Toub <stoub@microsoft.com>
Sat, 21 Mar 2020 22:01:49 +0000 (18:01 -0400)
committerGitHub <noreply@github.com>
Sat, 21 Mar 2020 22:01:49 +0000 (18:01 -0400)
55 files changed:
src/libraries/Common/src/System/Net/ContextAwareResult.cs
src/libraries/Common/src/System/Net/Mail/MailBnfHelper.cs
src/libraries/Common/src/System/Net/NTAuthentication.Common.cs
src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Unix.cs
src/libraries/Common/src/System/Net/Security/NegotiateStreamPal.Windows.cs
src/libraries/Common/src/System/Net/TlsStream.cs
src/libraries/System.Net.Mail/ref/System.Net.Mail.cs
src/libraries/System.Net.Mail/ref/System.Net.Mail.csproj
src/libraries/System.Net.Mail/src/System.Net.Mail.csproj
src/libraries/System.Net.Mail/src/System/Net/Base64Stream.cs
src/libraries/System.Net.Mail/src/System/Net/BufferBuilder.cs
src/libraries/System.Net.Mail/src/System/Net/BufferedReadStream.cs
src/libraries/System.Net.Mail/src/System/Net/CloseableStream.cs
src/libraries/System.Net.Mail/src/System/Net/DelegatedStream.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/AlternateView.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/AlternateViewCollection.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/Attachment.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/ISmtpAuthenticationModule.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/LinkedResource.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/MailAddress.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/MailHeaderInfo.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/MailMessage.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/MailPriority.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/MailWriter.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpClient.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpCommands.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpConnection.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpException.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpFailedRecipientException.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpFailedRecipientsException.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpLoginAuthenticationModule.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNegotiateAuthenticationModule.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpNtlmAuthenticationModule.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReader.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpReplyReaderFactory.cs
src/libraries/System.Net.Mail/src/System/Net/Mail/SmtpTransport.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/BaseWriter.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/ContentDisposition.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/ContentType.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/EightBitStream.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/HeaderCollection.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/MimeBasePart.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/MimeMultiPart.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/MimePart.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/MimeWriter.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/MultiAsyncResult.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/QEncodedStream.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/QuotedPrintableStream.cs
src/libraries/System.Net.Mail/src/System/Net/Mime/WriteStateInfoBase.cs
src/libraries/System.Net.Mail/src/System/Net/TrackingStringDictionary.cs
src/libraries/System.Net.Mail/src/System/Net/TrackingValidationObjectDictionary.cs
src/libraries/System.Net.Mail/tests/Unit/System.Net.Mail.Unit.Tests.csproj
src/libraries/System.Net.Security/src/System/Net/NTAuthentication.cs
src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Unix.cs
src/libraries/System.Net.Security/src/System/Net/Security/NegotiateStreamPal.Windows.cs

index bf8942c..b6391b8 100644 (file)
@@ -98,11 +98,11 @@ namespace System.Net
         //
         // Setting forceCaptureContext enables the ContextCopy property even when a null callback is specified.  (The context is
         // always captured if a callback is given.)
-        internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, object myObject, object? myState, AsyncCallback? myCallBack) :
+        internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, object? myObject, object? myState, AsyncCallback? myCallBack) :
             this(captureIdentity, forceCaptureContext, false, myObject, myState, myCallBack)
         { }
 
-        internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object myObject, object? myState, AsyncCallback? myCallBack) :
+        internal ContextAwareResult(bool captureIdentity, bool forceCaptureContext, bool threadSafeContextCopy, object? myObject, object? myState, AsyncCallback? myCallBack) :
             base(myObject, myState, myCallBack)
         {
             if (forceCaptureContext)
index bd368ce..5f72eaf 100644 (file)
@@ -190,7 +190,7 @@ namespace System.Net.Mime
                 throw new FormatException(SR.InvalidHeaderName);
         }
 
-        internal static string? ReadQuotedString(string data, ref int offset, StringBuilder builder)
+        internal static string? ReadQuotedString(string data, ref int offset, StringBuilder? builder)
         {
             return ReadQuotedString(data, ref offset, builder, false, false);
         }
@@ -247,7 +247,7 @@ namespace System.Net.Mime
             throw new FormatException(SR.MailHeaderFieldMalformedHeader);
         }
 
-        internal static string? ReadParameterAttribute(string data, ref int offset, StringBuilder builder)
+        internal static string? ReadParameterAttribute(string data, ref int offset, StringBuilder? builder)
         {
             if (!SkipCFWS(data, ref offset))
                 return null; //
index 839c96f..9263131 100644 (file)
@@ -4,6 +4,7 @@
 
 #nullable enable
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Net.Security;
 using System.Runtime.InteropServices;
 using System.Security.Authentication.ExtendedProtection;
@@ -16,7 +17,7 @@ namespace System.Net
 
         private SafeFreeCredentials? _credentialsHandle;
         private SafeDeleteContext? _securityContext;
-        private string _spn = null!;
+        private string? _spn;
 
         private int _tokenSize;
         private ContextFlagsPal _requestedContextFlags;
@@ -92,12 +93,12 @@ namespace System.Net
         //
         // This overload does not attempt to impersonate because the caller either did it already or the original thread context is still preserved.
         //
-        internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string spn, ContextFlagsPal requestedContextFlags, ChannelBinding? channelBinding)
+        internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string? spn, ContextFlagsPal requestedContextFlags, ChannelBinding? channelBinding)
         {
             Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding);
         }
 
-        private void Initialize(bool isServer, string package, NetworkCredential credential, string spn, ContextFlagsPal requestedContextFlags, ChannelBinding? channelBinding)
+        private void Initialize(bool isServer, string package, NetworkCredential credential, string? spn, ContextFlagsPal requestedContextFlags, ChannelBinding? channelBinding)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, package, spn, requestedContextFlags);
 
@@ -162,7 +163,7 @@ namespace System.Net
             return NegotiateStreamPal.VerifySignature(_securityContext!, buffer, offset, count);
         }
 
-        internal int MakeSignature(byte[] buffer, int offset, int count, ref byte[] output)
+        internal int MakeSignature(byte[] buffer, int offset, int count, [AllowNull] ref byte[] output)
         {
             return NegotiateStreamPal.MakeSignature(_securityContext!, buffer, offset, count, ref output);
         }
@@ -202,7 +203,7 @@ namespace System.Net
             return outgoingBlob;
         }
 
-        internal byte[]? GetOutgoingBlob(byte[] incomingBlob, bool thrownOnError)
+        internal byte[]? GetOutgoingBlob(byte[]? incomingBlob, bool thrownOnError)
         {
             SecurityStatusPal statusCode;
             return GetOutgoingBlob(incomingBlob, thrownOnError, out statusCode);
index 441706c..21edf85 100644 (file)
@@ -6,6 +6,7 @@
 using System.IO;
 using System.ComponentModel;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Runtime.InteropServices;
 using System.Security;
 using System.Security.Authentication;
@@ -280,7 +281,7 @@ namespace System.Net.Security
           SafeFreeNegoCredentials credential,
           ref SafeDeleteContext? context,
           ChannelBinding? channelBinding,
-          string targetName,
+          string? targetName,
           ContextFlagsPal inFlags,
           byte[]? incomingBlob,
           ref byte[]? resultBuffer,
@@ -296,7 +297,7 @@ namespace System.Net.Security
                     NetEventSource.Info(context, $"requested protocol = {protocol}, target = {targetName}");
                 }
 
-                context = new SafeDeleteNegoContext(credential, targetName);
+                context = new SafeDeleteNegoContext(credential, targetName!);
             }
 
             SafeDeleteNegoContext negoContext = (SafeDeleteNegoContext)context;
@@ -358,7 +359,7 @@ namespace System.Net.Security
         internal static SecurityStatusPal InitializeSecurityContext(
             ref SafeFreeCredentials credentialsHandle,
             ref SafeDeleteContext? securityContext,
-            string spn,
+            string? spn,
             ContextFlagsPal requestedContextFlags,
             byte[]? incomingBlob,
             ChannelBinding? channelBinding,
@@ -624,7 +625,7 @@ namespace System.Net.Security
             return GssUnwrap(((SafeDeleteNegoContext)securityContext).GssContext, buffer!, offset, count);
         }
 
-        internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, ref byte[] output)
+        internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, [AllowNull] ref byte[] output)
         {
             SafeDeleteNegoContext gssContext = (SafeDeleteNegoContext)securityContext;
             byte[] tempOutput = GssWrap(gssContext.GssContext, false, buffer, offset, count);
index 56a8793..617f324 100644 (file)
@@ -5,6 +5,7 @@
 #nullable enable
 using System.ComponentModel;
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Globalization;
 using System.Runtime.InteropServices;
 using System.Security.Authentication.ExtendedProtection;
@@ -74,7 +75,7 @@ namespace System.Net.Security
         internal static SecurityStatusPal InitializeSecurityContext(
             ref SafeFreeCredentials? credentialsHandle,
             ref SafeDeleteContext? securityContext,
-            string spn,
+            string? spn,
             ContextFlagsPal requestedContextFlags,
             byte[]? incomingBlob,
             ChannelBinding? channelBinding,
@@ -225,7 +226,7 @@ namespace System.Net.Security
             return securityBuffer[1].size;
         }
 
-        internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, ref byte[] output)
+        internal static int MakeSignature(SafeDeleteContext securityContext, byte[] buffer, int offset, int count, [AllowNull] ref byte[] output)
         {
             SecPkgContext_Sizes sizes = default;
             bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_SIZES, ref sizes);
index 9be73c9..456fbea 100644 (file)
@@ -14,9 +14,9 @@ namespace System.Net
     {
         private readonly SslStream _sslStream;
         private readonly string _host;
-        private readonly X509CertificateCollection _clientCertificates;
+        private readonly X509CertificateCollection? _clientCertificates;
 
-        public TlsStream(NetworkStream stream, Socket socket, string host, X509CertificateCollection clientCertificates) : base(socket)
+        public TlsStream(NetworkStream stream, Socket socket, string host, X509CertificateCollection? clientCertificates) : base(socket)
         {
             _sslStream = new SslStream(stream, false, ServicePointManager.ServerCertificateValidationCallback);
             _host = host;
index c10324b..5b68a8b 100644 (file)
@@ -10,16 +10,16 @@ namespace System.Net.Mail
     public partial class AlternateView : System.Net.Mail.AttachmentBase
     {
         public AlternateView(System.IO.Stream contentStream) : base (default(System.IO.Stream)) { }
-        public AlternateView(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
-        public AlternateView(System.IO.Stream contentStream, string mediaType) : base (default(System.IO.Stream)) { }
+        public AlternateView(System.IO.Stream contentStream, System.Net.Mime.ContentType? contentType) : base (default(System.IO.Stream)) { }
+        public AlternateView(System.IO.Stream contentStream, string? mediaType) : base (default(System.IO.Stream)) { }
         public AlternateView(string fileName) : base (default(System.IO.Stream)) { }
-        public AlternateView(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
-        public AlternateView(string fileName, string mediaType) : base (default(System.IO.Stream)) { }
-        public System.Uri BaseUri { get { throw null; } set { } }
+        public AlternateView(string fileName, System.Net.Mime.ContentType? contentType) : base (default(System.IO.Stream)) { }
+        public AlternateView(string fileName, string? mediaType) : base (default(System.IO.Stream)) { }
+        public System.Uri? BaseUri { get { throw null; } set { } }
         public System.Net.Mail.LinkedResourceCollection LinkedResources { get { throw null; } }
         public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content) { throw null; }
-        public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Net.Mime.ContentType contentType) { throw null; }
-        public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Text.Encoding contentEncoding, string mediaType) { throw null; }
+        public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Net.Mime.ContentType? contentType) { throw null; }
+        public static System.Net.Mail.AlternateView CreateAlternateViewFromString(string content, System.Text.Encoding? contentEncoding, string? mediaType) { throw null; }
         protected override void Dispose(bool disposing) { }
     }
     public sealed partial class AlternateViewCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.AlternateView>, System.IDisposable
@@ -34,26 +34,27 @@ namespace System.Net.Mail
     public partial class Attachment : System.Net.Mail.AttachmentBase
     {
         public Attachment(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
-        public Attachment(System.IO.Stream contentStream, string name) : base (default(System.IO.Stream)) { }
-        public Attachment(System.IO.Stream contentStream, string name, string mediaType) : base (default(System.IO.Stream)) { }
+        public Attachment(System.IO.Stream contentStream, string? name) : base (default(System.IO.Stream)) { }
+        public Attachment(System.IO.Stream contentStream, string? name, string? mediaType) : base (default(System.IO.Stream)) { }
         public Attachment(string fileName) : base (default(System.IO.Stream)) { }
         public Attachment(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
-        public Attachment(string fileName, string mediaType) : base (default(System.IO.Stream)) { }
-        public System.Net.Mime.ContentDisposition ContentDisposition { get { throw null; } }
-        public string Name { get { throw null; } set { } }
-        public System.Text.Encoding NameEncoding { get { throw null; } set { } }
+        public Attachment(string fileName, string? mediaType) : base (default(System.IO.Stream)) { }
+        public System.Net.Mime.ContentDisposition? ContentDisposition { get { throw null; } }
+        public string? Name { get { throw null; } set { } }
+        public System.Text.Encoding? NameEncoding { get { throw null; } set { } }
         public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, System.Net.Mime.ContentType contentType) { throw null; }
-        public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string name) { throw null; }
-        public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string name, System.Text.Encoding contentEncoding, string mediaType) { throw null; }
+        public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string? name) { throw null; }
+        public static System.Net.Mail.Attachment CreateAttachmentFromString(string content, string? name, System.Text.Encoding? contentEncoding, string mediaType) { throw null; }
     }
     public abstract partial class AttachmentBase : System.IDisposable
     {
         protected AttachmentBase(System.IO.Stream contentStream) { }
-        protected AttachmentBase(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) { }
-        protected AttachmentBase(System.IO.Stream contentStream, string mediaType) { }
+        protected AttachmentBase(System.IO.Stream contentStream, System.Net.Mime.ContentType? contentType) { }
+        protected AttachmentBase(System.IO.Stream contentStream, string? mediaType) { }
         protected AttachmentBase(string fileName) { }
-        protected AttachmentBase(string fileName, System.Net.Mime.ContentType contentType) { }
-        protected AttachmentBase(string fileName, string mediaType) { }
+        protected AttachmentBase(string fileName, System.Net.Mime.ContentType? contentType) { }
+        protected AttachmentBase(string fileName, string? mediaType) { }
+        [System.Diagnostics.CodeAnalysis.AllowNull]
         public string ContentId { get { throw null; } set { } }
         public System.IO.Stream ContentStream { get { throw null; } }
         public System.Net.Mime.ContentType ContentType { get { throw null; } set { } }
@@ -82,15 +83,15 @@ namespace System.Net.Mail
     public partial class LinkedResource : System.Net.Mail.AttachmentBase
     {
         public LinkedResource(System.IO.Stream contentStream) : base (default(System.IO.Stream)) { }
-        public LinkedResource(System.IO.Stream contentStream, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
-        public LinkedResource(System.IO.Stream contentStream, string mediaType) : base (default(System.IO.Stream)) { }
+        public LinkedResource(System.IO.Stream contentStream, System.Net.Mime.ContentType? contentType) : base (default(System.IO.Stream)) { }
+        public LinkedResource(System.IO.Stream contentStream, string? mediaType) : base (default(System.IO.Stream)) { }
         public LinkedResource(string fileName) : base (default(System.IO.Stream)) { }
-        public LinkedResource(string fileName, System.Net.Mime.ContentType contentType) : base (default(System.IO.Stream)) { }
-        public LinkedResource(string fileName, string mediaType) : base (default(System.IO.Stream)) { }
-        public System.Uri ContentLink { get { throw null; } set { } }
+        public LinkedResource(string fileName, System.Net.Mime.ContentType? contentType) : base (default(System.IO.Stream)) { }
+        public LinkedResource(string fileName, string? mediaType) : base (default(System.IO.Stream)) { }
+        public System.Uri? ContentLink { get { throw null; } set { } }
         public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content) { throw null; }
-        public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Net.Mime.ContentType contentType) { throw null; }
-        public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Text.Encoding contentEncoding, string mediaType) { throw null; }
+        public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Net.Mime.ContentType? contentType) { throw null; }
+        public static System.Net.Mail.LinkedResource CreateLinkedResourceFromString(string content, System.Text.Encoding? contentEncoding, string? mediaType) { throw null; }
     }
     public sealed partial class LinkedResourceCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.LinkedResource>, System.IDisposable
     {
@@ -104,17 +105,17 @@ namespace System.Net.Mail
     public partial class MailAddress
     {
         public MailAddress(string address) { }
-        public MailAddress(string address, string displayName) { }
-        public MailAddress(string address, string displayName, System.Text.Encoding displayNameEncoding) { }
+        public MailAddress(string address, string? displayName) { }
+        public MailAddress(string address, string? displayName, System.Text.Encoding? displayNameEncoding) { }
         public string Address { get { throw null; } }
         public string DisplayName { get { throw null; } }
         public string Host { get { throw null; } }
         public string User { get { throw null; } }
-        public override bool Equals(object value) { throw null; }
+        public override bool Equals(object? value) { throw null; }
         public override int GetHashCode() { throw null; }
-        public static bool TryCreate(string address, out MailAddress result) { throw null; }
-        public static bool TryCreate(string address, string displayName, out MailAddress result) { throw null; }
-        public static bool TryCreate(string address, string displayName, System.Text.Encoding displayNameEncoding, out MailAddress result) { throw null; }
+        public static bool TryCreate(string address, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out MailAddress? result) { throw null; }
+        public static bool TryCreate(string address, string? displayName, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out MailAddress? result) { throw null; }
+        public static bool TryCreate(string address, string? displayName, System.Text.Encoding displayNameEncoding, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out MailAddress? result) { throw null; }
         public override string ToString() { throw null; }
     }
     public partial class MailAddressCollection : System.Collections.ObjectModel.Collection<System.Net.Mail.MailAddress>
@@ -130,26 +131,30 @@ namespace System.Net.Mail
         public MailMessage() { }
         public MailMessage(System.Net.Mail.MailAddress from, System.Net.Mail.MailAddress to) { }
         public MailMessage(string from, string to) { }
-        public MailMessage(string from, string to, string subject, string body) { }
+        public MailMessage(string from, string to, string? subject, string? body) { }
         public System.Net.Mail.AlternateViewCollection AlternateViews { get { throw null; } }
         public System.Net.Mail.AttachmentCollection Attachments { get { throw null; } }
         public System.Net.Mail.MailAddressCollection Bcc { get { throw null; } }
+        [System.Diagnostics.CodeAnalysis.AllowNull]
         public string Body { get { throw null; } set { } }
-        public System.Text.Encoding BodyEncoding { get { throw null; } set { } }
+        public System.Text.Encoding? BodyEncoding { get { throw null; } set { } }
         public System.Net.Mime.TransferEncoding BodyTransferEncoding { get { throw null; } set { } }
         public System.Net.Mail.MailAddressCollection CC { get { throw null; } }
         public System.Net.Mail.DeliveryNotificationOptions DeliveryNotificationOptions { get { throw null; } set { } }
-        public System.Net.Mail.MailAddress From { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.DisallowNull]
+        public System.Net.Mail.MailAddress? From { get { throw null; } set { } }
         public System.Collections.Specialized.NameValueCollection Headers { get { throw null; } }
-        public System.Text.Encoding HeadersEncoding { get { throw null; } set { } }
+        public System.Text.Encoding? HeadersEncoding { get { throw null; } set { } }
         public bool IsBodyHtml { get { throw null; } set { } }
         public System.Net.Mail.MailPriority Priority { get { throw null; } set { } }
         [System.ObsoleteAttribute("ReplyTo is obsoleted for this type.  Please use ReplyToList instead which can accept multiple addresses. https://go.microsoft.com/fwlink/?linkid=14202")]
-        public System.Net.Mail.MailAddress ReplyTo { get { throw null; } set { } }
+        public System.Net.Mail.MailAddress? ReplyTo { get { throw null; } set { } }
         public System.Net.Mail.MailAddressCollection ReplyToList { get { throw null; } }
-        public System.Net.Mail.MailAddress Sender { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.DisallowNull]
+        public System.Net.Mail.MailAddress? Sender { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.AllowNull]
         public string Subject { get { throw null; } set { } }
-        public System.Text.Encoding SubjectEncoding { get { throw null; } set { } }
+        public System.Text.Encoding? SubjectEncoding { get { throw null; } set { } }
         public System.Net.Mail.MailAddressCollection To { get { throw null; } }
         public void Dispose() { }
         protected virtual void Dispose(bool disposing) { }
@@ -164,33 +169,34 @@ namespace System.Net.Mail
     public partial class SmtpClient : System.IDisposable
     {
         public SmtpClient() { }
-        public SmtpClient(string host) { }
-        public SmtpClient(string host, int port) { }
+        public SmtpClient(string? host) { }
+        public SmtpClient(string? host, int port) { }
         public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates { get { throw null; } }
-        public System.Net.ICredentialsByHost Credentials { get { throw null; } set { } }
+        public System.Net.ICredentialsByHost? Credentials { get { throw null; } set { } }
         public System.Net.Mail.SmtpDeliveryFormat DeliveryFormat { get { throw null; } set { } }
         public System.Net.Mail.SmtpDeliveryMethod DeliveryMethod { get { throw null; } set { } }
         public bool EnableSsl { get { throw null; } set { } }
-        public string Host { get { throw null; } set { } }
-        public string PickupDirectoryLocation { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.DisallowNull]
+        public string? Host { get { throw null; } set { } }
+        public string? PickupDirectoryLocation { get { throw null; } set { } }
         public int Port { get { throw null; } set { } }
         public System.Net.ServicePoint ServicePoint { get { throw null; } }
-        public string TargetName { get { throw null; } set { } }
+        public string? TargetName { get { throw null; } set { } }
         public int Timeout { get { throw null; } set { } }
         public bool UseDefaultCredentials { get { throw null; } set { } }
-        public event System.Net.Mail.SendCompletedEventHandler SendCompleted { add { } remove { } }
+        public event System.Net.Mail.SendCompletedEventHandler? SendCompleted { add { } remove { } }
         public void Dispose() { }
         protected virtual void Dispose(bool disposing) { }
         protected void OnSendCompleted(System.ComponentModel.AsyncCompletedEventArgs e) { }
         public void Send(System.Net.Mail.MailMessage message) { }
-        public void Send(string from, string recipients, string subject, string body) { }
-        public void SendAsync(System.Net.Mail.MailMessage message, object userToken) { }
-        public void SendAsync(string from, string recipients, string subject, string body, object userToken) { }
+        public void Send(string from, string recipients, string? subject, string? body) { }
+        public void SendAsync(System.Net.Mail.MailMessage message, object? userToken) { }
+        public void SendAsync(string from, string recipients, string? subject, string? body, object? userToken) { }
         public void SendAsyncCancel() { }
         public System.Threading.Tasks.Task SendMailAsync(System.Net.Mail.MailMessage message) { throw null; }
-        public System.Threading.Tasks.Task SendMailAsync(string from, string recipients, string subject, string body) { throw null; }
+        public System.Threading.Tasks.Task SendMailAsync(string from, string recipients, string? subject, string? body) { throw null; }
         public System.Threading.Tasks.Task SendMailAsync(System.Net.Mail.MailMessage message, System.Threading.CancellationToken cancellationToken) { throw null; }
-        public System.Threading.Tasks.Task SendMailAsync(string from, string recipients, string subject, string body, System.Threading.CancellationToken cancellationToken) { throw null; }
+        public System.Threading.Tasks.Task SendMailAsync(string from, string recipients, string? subject, string? body, System.Threading.CancellationToken cancellationToken) { throw null; }
     }
     public enum SmtpDeliveryFormat
     {
@@ -207,10 +213,10 @@ namespace System.Net.Mail
     {
         public SmtpException() { }
         public SmtpException(System.Net.Mail.SmtpStatusCode statusCode) { }
-        public SmtpException(System.Net.Mail.SmtpStatusCode statusCode, string message) { }
+        public SmtpException(System.Net.Mail.SmtpStatusCode statusCode, string? message) { }
         protected SmtpException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
-        public SmtpException(string message) { }
-        public SmtpException(string message, System.Exception innerException) { }
+        public SmtpException(string? message) { }
+        public SmtpException(string? message, System.Exception? innerException) { }
         public System.Net.Mail.SmtpStatusCode StatusCode { get { throw null; } set { } }
         public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
         void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
@@ -218,13 +224,13 @@ namespace System.Net.Mail
     public partial class SmtpFailedRecipientException : System.Net.Mail.SmtpException, System.Runtime.Serialization.ISerializable
     {
         public SmtpFailedRecipientException() { }
-        public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string failedRecipient) { }
-        public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string failedRecipient, string serverResponse) { }
+        public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string? failedRecipient) { }
+        public SmtpFailedRecipientException(System.Net.Mail.SmtpStatusCode statusCode, string? failedRecipient, string? serverResponse) { }
         protected SmtpFailedRecipientException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
-        public SmtpFailedRecipientException(string message) { }
-        public SmtpFailedRecipientException(string message, System.Exception innerException) { }
-        public SmtpFailedRecipientException(string message, string failedRecipient, System.Exception innerException) { }
-        public string FailedRecipient { get { throw null; } }
+        public SmtpFailedRecipientException(string? message) { }
+        public SmtpFailedRecipientException(string? message, System.Exception? innerException) { }
+        public SmtpFailedRecipientException(string? message, string? failedRecipient, System.Exception? innerException) { }
+        public string? FailedRecipient { get { throw null; } }
         public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
         void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
     }
@@ -232,9 +238,9 @@ namespace System.Net.Mail
     {
         public SmtpFailedRecipientsException() { }
         protected SmtpFailedRecipientsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
-        public SmtpFailedRecipientsException(string message) { }
-        public SmtpFailedRecipientsException(string message, System.Exception innerException) { }
-        public SmtpFailedRecipientsException(string message, System.Net.Mail.SmtpFailedRecipientException[] innerExceptions) { }
+        public SmtpFailedRecipientsException(string? message) { }
+        public SmtpFailedRecipientsException(string? message, System.Exception? innerException) { }
+        public SmtpFailedRecipientsException(string? message, System.Net.Mail.SmtpFailedRecipientException[] innerExceptions) { }
         public System.Net.Mail.SmtpFailedRecipientException[] InnerExceptions { get { throw null; } }
         public override void GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
         void System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
@@ -276,13 +282,13 @@ namespace System.Net.Mime
         public ContentDisposition(string disposition) { }
         public System.DateTime CreationDate { get { throw null; } set { } }
         public string DispositionType { get { throw null; } set { } }
-        public string FileName { get { throw null; } set { } }
+        public string? FileName { get { throw null; } set { } }
         public bool Inline { get { throw null; } set { } }
         public System.DateTime ModificationDate { get { throw null; } set { } }
         public System.Collections.Specialized.StringDictionary Parameters { get { throw null; } }
         public System.DateTime ReadDate { get { throw null; } set { } }
         public long Size { get { throw null; } set { } }
-        public override bool Equals(object rparam) { throw null; }
+        public override bool Equals(object? rparam) { throw null; }
         public override int GetHashCode() { throw null; }
         public override string ToString() { throw null; }
     }
@@ -290,12 +296,13 @@ namespace System.Net.Mime
     {
         public ContentType() { }
         public ContentType(string contentType) { }
-        public string Boundary { get { throw null; } set { } }
-        public string CharSet { get { throw null; } set { } }
+        public string? Boundary { get { throw null; } set { } }
+        public string? CharSet { get { throw null; } set { } }
         public string MediaType { get { throw null; } set { } }
+        [System.Diagnostics.CodeAnalysis.AllowNull]
         public string Name { get { throw null; } set { } }
         public System.Collections.Specialized.StringDictionary Parameters { get { throw null; } }
-        public override bool Equals(object rparam) { throw null; }
+        public override bool Equals(object? rparam) { throw null; }
         public override int GetHashCode() { throw null; }
         public override string ToString() { throw null; }
     }
index 56ce440..99ae2fb 100644 (file)
@@ -1,6 +1,7 @@
 <Project Sdk="Microsoft.NET.Sdk">
   <PropertyGroup>
     <TargetFrameworks>$(NetCoreAppCurrent)</TargetFrameworks>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="System.Net.Mail.cs" />
index fe0aadd..babcb1d 100644 (file)
@@ -2,6 +2,7 @@
   <PropertyGroup>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix</TargetFrameworks>
+    <Nullable>enable</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="System\Net\Base64Stream.cs" />
index 437173e..2d46e61 100644 (file)
@@ -43,7 +43,7 @@ namespace System.Net
 
         private readonly int _lineLength;
         private readonly Base64WriteStateInfo _writeState;
-        private ReadStateInfo _readState;
+        private ReadStateInfo? _readState;
 
         //the number of bytes needed to encode three bytes (see algorithm description in Encode method below)
         private const int SizeOfBase64EncodedChar = 4;
@@ -74,7 +74,7 @@ namespace System.Net
             }
         }
 
-        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
         {
             if (buffer == null)
             {
@@ -94,7 +94,7 @@ namespace System.Net
             return result;
         }
 
-        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
         {
             if (buffer == null)
             {
@@ -416,7 +416,7 @@ namespace System.Net
 
             private static readonly AsyncCallback s_onRead = OnRead;
 
-            internal ReadAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
+            internal ReadAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) : base(null, state, callback)
             {
                 _parent = parent;
                 _buffer = buffer;
@@ -465,7 +465,7 @@ namespace System.Net
             {
                 if (!result.CompletedSynchronously)
                 {
-                    ReadAsyncResult thisPtr = (ReadAsyncResult)result.AsyncState;
+                    ReadAsyncResult thisPtr = (ReadAsyncResult)result.AsyncState!;
                     try
                     {
                         if (!thisPtr.CompleteRead(result))
@@ -502,7 +502,7 @@ namespace System.Net
             private readonly int _count;
             private int _written;
 
-            internal WriteAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
+            internal WriteAsyncResult(Base64Stream parent, byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) : base(null, state, callback)
             {
                 _parent = parent;
                 _buffer = buffer;
@@ -544,7 +544,7 @@ namespace System.Net
             {
                 if (!result.CompletedSynchronously)
                 {
-                    WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState;
+                    WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState!;
                     try
                     {
                         thisPtr.CompleteWrite(result);
index dc40162..3a6806e 100644 (file)
@@ -47,12 +47,12 @@ namespace System.Net.Mail
             _offset += count;
         }
 
-        internal void Append(string value)
+        internal void Append(string? value)
         {
             Append(value, false);
         }
 
-        internal void Append(string value, bool allowUnicode)
+        internal void Append(string? value, bool allowUnicode)
         {
             if (string.IsNullOrEmpty(value))
             {
index 3f5194e..95f851e 100644 (file)
@@ -11,7 +11,7 @@ namespace System.Net
 {
     internal class BufferedReadStream : DelegatedStream
     {
-        private byte[] _storedBuffer;
+        private byte[]? _storedBuffer;
         private int _storedLength;
         private int _storedOffset;
         private readonly bool _readMore;
@@ -41,7 +41,7 @@ namespace System.Net
             }
         }
 
-        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
         {
             ReadAsyncResult result = new ReadAsyncResult(this, callback, state);
             result.Read(buffer, offset, count);
@@ -60,7 +60,7 @@ namespace System.Net
             if (_storedOffset < _storedLength)
             {
                 read = Math.Min(count, _storedLength - _storedOffset);
-                Buffer.BlockCopy(_storedBuffer, _storedOffset, buffer, offset, read);
+                Buffer.BlockCopy(_storedBuffer!, _storedOffset, buffer, offset, read);
                 _storedOffset += read;
                 if (read == count || !_readMore)
                 {
@@ -82,7 +82,7 @@ namespace System.Net
             }
 
             read = Math.Min(count, _storedLength - _storedOffset);
-            Buffer.BlockCopy(_storedBuffer, _storedOffset, buffer, offset, read);
+            Buffer.BlockCopy(_storedBuffer!, _storedOffset, buffer, offset, read);
             _storedOffset += read;
             if (read == count || !_readMore)
             {
@@ -105,7 +105,7 @@ namespace System.Net
         {
             if (_storedOffset < _storedLength)
             {
-                return (int)_storedBuffer[_storedOffset++];
+                return _storedBuffer![_storedOffset++];
             }
             else
             {
@@ -139,7 +139,7 @@ namespace System.Net
                     _storedOffset -= count;
                 }
                 // if there's room in the buffer but need to shift things over
-                else if (count <= _storedBuffer.Length - _storedLength + _storedOffset)
+                else if (count <= _storedBuffer!.Length - _storedLength + _storedOffset)
                 {
                     Buffer.BlockCopy(_storedBuffer, _storedOffset, _storedBuffer, count, _storedLength - _storedOffset);
                     _storedLength += count - _storedOffset;
@@ -155,7 +155,7 @@ namespace System.Net
                 }
             }
 
-            Buffer.BlockCopy(buffer, offset, _storedBuffer, _storedOffset, count);
+            Buffer.BlockCopy(buffer, offset, _storedBuffer!, _storedOffset, count);
         }
 
         private class ReadAsyncResult : LazyAsyncResult
@@ -164,7 +164,7 @@ namespace System.Net
             private int _read;
             private static readonly AsyncCallback s_onRead = new AsyncCallback(OnRead);
 
-            internal ReadAsyncResult(BufferedReadStream parent, AsyncCallback callback, object state) : base(null, state, callback)
+            internal ReadAsyncResult(BufferedReadStream parent, AsyncCallback? callback, object? state) : base(null, state, callback)
             {
                 _parent = parent;
             }
@@ -174,7 +174,7 @@ namespace System.Net
                 if (_parent._storedOffset < _parent._storedLength)
                 {
                     _read = Math.Min(count, _parent._storedLength - _parent._storedOffset);
-                    Buffer.BlockCopy(_parent._storedBuffer, _parent._storedOffset, buffer, offset, _read);
+                    Buffer.BlockCopy(_parent._storedBuffer!, _parent._storedOffset, buffer, offset, _read);
                     _parent._storedOffset += _read;
                     if (_read == count || !_parent._readMore)
                     {
@@ -204,7 +204,7 @@ namespace System.Net
             {
                 if (!result.CompletedSynchronously)
                 {
-                    ReadAsyncResult thisPtr = (ReadAsyncResult)result.AsyncState;
+                    ReadAsyncResult thisPtr = (ReadAsyncResult)result.AsyncState!;
                     try
                     {
                         thisPtr._read += thisPtr._parent.BaseStream.EndRead(result);
index 5dc9f46..32dd324 100644 (file)
@@ -10,10 +10,10 @@ namespace System.Net
     /// <summary>Provides a stream that notifies an event when the Close method is called.</summary>
     internal class ClosableStream : DelegatedStream
     {
-        private readonly EventHandler _onClose;
+        private readonly EventHandler? _onClose;
         private int _closed;
 
-        internal ClosableStream(Stream stream, EventHandler onClose) : base(stream)
+        internal ClosableStream(Stream stream, EventHandler? onClose) : base(stream)
         {
             _onClose = onClose;
         }
index 9515efe..5655332 100644 (file)
@@ -12,7 +12,6 @@ namespace System.Net
     internal class DelegatedStream : Stream
     {
         private readonly Stream _stream;
-        private readonly NetworkStream _netStream;
 
         protected DelegatedStream(Stream stream)
         {
@@ -20,7 +19,6 @@ namespace System.Net
                 throw new ArgumentNullException(nameof(stream));
 
             _stream = stream;
-            _netStream = stream as NetworkStream;
         }
 
         protected Stream BaseStream
@@ -84,40 +82,20 @@ namespace System.Net
             }
         }
 
-        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
         {
             if (!CanRead)
                 throw new NotSupportedException(SR.ReadNotSupported);
 
-            IAsyncResult result = null;
-
-            if (_netStream != null)
-            {
-                result = _netStream.BeginRead(buffer, offset, count, callback, state);
-            }
-            else
-            {
-                result = _stream.BeginRead(buffer, offset, count, callback, state);
-            }
-            return result;
+            return _stream.BeginRead(buffer, offset, count, callback, state);
         }
 
-        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
         {
             if (!CanWrite)
                 throw new NotSupportedException(SR.WriteNotSupported);
 
-            IAsyncResult result = null;
-
-            if (_netStream != null)
-            {
-                result = _netStream.BeginWrite(buffer, offset, count, callback, state);
-            }
-            else
-            {
-                result = _stream.BeginWrite(buffer, offset, count, callback, state);
-            }
-            return result;
+            return _stream.BeginWrite(buffer, offset, count, callback, state);
         }
 
         //This calls close on the inner stream
index dd2d6b9..9a0661e 100644 (file)
@@ -2,7 +2,6 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
-using System;
 using System.IO;
 using System.Net.Mime;
 using System.Text;
@@ -11,21 +10,20 @@ namespace System.Net.Mail
 {
     public class AlternateView : AttachmentBase
     {
-        private LinkedResourceCollection _linkedResources;
+        private LinkedResourceCollection? _linkedResources;
 
         internal AlternateView()
         { }
 
-
         public AlternateView(string fileName) :
             base(fileName)
         { }
 
-        public AlternateView(string fileName, string mediaType) :
+        public AlternateView(string fileName, string? mediaType) :
             base(fileName, mediaType)
         { }
 
-        public AlternateView(string fileName, ContentType contentType) :
+        public AlternateView(string fileName, ContentType? contentType) :
             base(fileName, contentType)
         { }
 
@@ -33,11 +31,11 @@ namespace System.Net.Mail
             base(contentStream)
         { }
 
-        public AlternateView(Stream contentStream, string mediaType) :
+        public AlternateView(Stream contentStream, string? mediaType) :
             base(contentStream, mediaType)
         { }
 
-        public AlternateView(Stream contentStream, ContentType contentType) :
+        public AlternateView(Stream contentStream, ContentType? contentType) :
             base(contentStream, contentType)
         { }
 
@@ -50,16 +48,11 @@ namespace System.Net.Mail
                     throw new ObjectDisposedException(GetType().FullName);
                 }
 
-
-                if (_linkedResources == null)
-                {
-                    _linkedResources = new LinkedResourceCollection();
-                }
-                return _linkedResources;
+                return _linkedResources ??= new LinkedResourceCollection();
             }
         }
 
-        public Uri BaseUri
+        public Uri? BaseUri
         {
             get
             {
@@ -78,14 +71,14 @@ namespace System.Net.Mail
             return a;
         }
 
-        public static AlternateView CreateAlternateViewFromString(string content, Encoding contentEncoding, string mediaType)
+        public static AlternateView CreateAlternateViewFromString(string content, Encoding? contentEncoding, string? mediaType)
         {
             AlternateView a = new AlternateView();
             a.SetContentFromString(content, contentEncoding, mediaType);
             return a;
         }
 
-        public static AlternateView CreateAlternateViewFromString(string content, ContentType contentType)
+        public static AlternateView CreateAlternateViewFromString(string content, ContentType? contentType)
         {
             AlternateView a = new AlternateView();
             a.SetContentFromString(content, contentType);
index 90abcbf..87eb900 100644 (file)
@@ -2,7 +2,6 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
-using System;
 using System.Collections.ObjectModel;
 
 namespace System.Net.Mail
@@ -57,7 +56,6 @@ namespace System.Net.Mail
                 throw new ObjectDisposedException(GetType().FullName);
             }
 
-
             if (item == null)
             {
                 throw new ArgumentNullException(nameof(item));
index 491af5d..44e48f7 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Diagnostics.CodeAnalysis;
 using System.IO;
 using System.Net.Mime;
 using System.Text;
@@ -23,12 +24,12 @@ namespace System.Net.Mail
             SetContentFromFile(fileName, string.Empty);
         }
 
-        protected AttachmentBase(string fileName, string mediaType)
+        protected AttachmentBase(string fileName, string? mediaType)
         {
             SetContentFromFile(fileName, mediaType);
         }
 
-        protected AttachmentBase(string fileName, ContentType contentType)
+        protected AttachmentBase(string fileName, ContentType? contentType)
         {
             SetContentFromFile(fileName, contentType);
         }
@@ -38,17 +39,17 @@ namespace System.Net.Mail
             _part.SetContent(contentStream);
         }
 
-        protected AttachmentBase(Stream contentStream, string mediaType)
+        protected AttachmentBase(Stream contentStream, string? mediaType)
         {
             _part.SetContent(contentStream, null, mediaType);
         }
 
-        internal AttachmentBase(Stream contentStream, string name, string mediaType)
+        internal AttachmentBase(Stream contentStream, string? name, string? mediaType)
         {
             _part.SetContent(contentStream, name, mediaType);
         }
 
-        protected AttachmentBase(Stream contentStream, ContentType contentType)
+        protected AttachmentBase(Stream contentStream, ContentType? contentType)
         {
             _part.SetContent(contentStream, contentType);
         }
@@ -67,7 +68,7 @@ namespace System.Net.Mail
             }
         }
 
-        internal void SetContentFromFile(string fileName, ContentType contentType)
+        internal void SetContentFromFile(string fileName, ContentType? contentType)
         {
             if (fileName == null)
             {
@@ -83,7 +84,7 @@ namespace System.Net.Mail
             _part.SetContent(stream, contentType);
         }
 
-        internal void SetContentFromFile(string fileName, string mediaType)
+        internal void SetContentFromFile(string fileName, string? mediaType)
         {
             if (fileName == null)
             {
@@ -99,7 +100,7 @@ namespace System.Net.Mail
             _part.SetContent(stream, null, mediaType);
         }
 
-        internal void SetContentFromString(string content, ContentType contentType)
+        internal void SetContentFromString(string content, ContentType? contentType)
         {
             if (content == null)
             {
@@ -141,7 +142,7 @@ namespace System.Net.Mail
             }
         }
 
-        internal void SetContentFromString(string content, Encoding encoding, string mediaType)
+        internal void SetContentFromString(string content, Encoding? encoding, string? mediaType)
         {
             if (content == null)
             {
@@ -220,15 +221,16 @@ namespace System.Net.Mail
                     throw new ObjectDisposedException(GetType().FullName);
                 }
 
-                return _part.Stream;
+                return _part.Stream!;
             }
         }
 
+        [AllowNull]
         public string ContentId
         {
             get
             {
-                string cid = _part.ContentID;
+                string? cid = _part.ContentID;
                 if (string.IsNullOrEmpty(cid))
                 {
                     cid = Guid.NewGuid().ToString();
@@ -285,11 +287,11 @@ namespace System.Net.Mail
             }
         }
 
-        internal Uri ContentLocation
+        internal Uri? ContentLocation
         {
             get
             {
-                Uri uri;
+                Uri? uri;
                 if (!Uri.TryCreate(_part.ContentLocation, UriKind.RelativeOrAbsolute, out uri))
                 {
                     return null;
@@ -314,8 +316,8 @@ namespace System.Net.Mail
 
     public class Attachment : AttachmentBase
     {
-        private string _name;
-        private Encoding _nameEncoding;
+        private string? _name;
+        private Encoding? _nameEncoding;
 
         internal Attachment()
         {
@@ -328,7 +330,7 @@ namespace System.Net.Mail
             MimePart.ContentDisposition = new ContentDisposition();
         }
 
-        public Attachment(string fileName, string mediaType) :
+        public Attachment(string fileName, string? mediaType) :
             base(fileName, mediaType)
         {
             Name = Path.GetFileName(fileName);
@@ -349,14 +351,14 @@ namespace System.Net.Mail
             MimePart.ContentDisposition = new ContentDisposition();
         }
 
-        public Attachment(Stream contentStream, string name) :
+        public Attachment(Stream contentStream, string? name) :
             base(contentStream, null, null)
         {
             Name = name;
             MimePart.ContentDisposition = new ContentDisposition();
         }
 
-        public Attachment(Stream contentStream, string name, string mediaType) :
+        public Attachment(Stream contentStream, string? name, string? mediaType) :
             base(contentStream, null, mediaType)
         {
             Name = name;
@@ -374,11 +376,7 @@ namespace System.Net.Mail
         {
             if (!allowUnicode && _name != null && _name.Length != 0 && !MimeBasePart.IsAscii(_name, false))
             {
-                Encoding encoding = NameEncoding;
-                if (encoding == null)
-                {
-                    encoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
-                }
+                Encoding encoding = NameEncoding ?? Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
                 MimePart.ContentType.Name = MimeBasePart.EncodeHeaderValue(_name, encoding, MimeBasePart.ShouldUseBase64Encoding(encoding));
             }
             else
@@ -387,7 +385,7 @@ namespace System.Net.Mail
             }
         }
 
-        public string Name
+        public string? Name
         {
             get
             {
@@ -395,7 +393,7 @@ namespace System.Net.Mail
             }
             set
             {
-                Encoding nameEncoding = MimeBasePart.DecodeEncoding(value);
+                Encoding? nameEncoding = MimeBasePart.DecodeEncoding(value);
                 if (nameEncoding != null)
                 {
                     _nameEncoding = nameEncoding;
@@ -412,8 +410,7 @@ namespace System.Net.Mail
             }
         }
 
-
-        public Encoding NameEncoding
+        public Encoding? NameEncoding
         {
             get
             {
@@ -429,7 +426,7 @@ namespace System.Net.Mail
             }
         }
 
-        public ContentDisposition ContentDisposition
+        public ContentDisposition? ContentDisposition
         {
             get
             {
@@ -446,7 +443,7 @@ namespace System.Net.Mail
             base.PrepareForSending(allowUnicode);
         }
 
-        public static Attachment CreateAttachmentFromString(string content, string name)
+        public static Attachment CreateAttachmentFromString(string content, string? name)
         {
             Attachment a = new Attachment();
             a.SetContentFromString(content, null, string.Empty);
@@ -454,7 +451,7 @@ namespace System.Net.Mail
             return a;
         }
 
-        public static Attachment CreateAttachmentFromString(string content, string name, Encoding contentEncoding, string mediaType)
+        public static Attachment CreateAttachmentFromString(string content, string? name, Encoding? contentEncoding, string? mediaType)
         {
             Attachment a = new Attachment();
             a.SetContentFromString(content, contentEncoding, mediaType);
index a96fbbf..9443578 100644 (file)
@@ -10,7 +10,7 @@ namespace System.Net.Mail
 {
     internal interface ISmtpAuthenticationModule
     {
-        Authorization Authenticate(string challenge, NetworkCredential credentials, object sessionCookie, string spn, ChannelBinding channelBindingToken);
+        Authorization? Authenticate(string? challenge, NetworkCredential? credentials, object sessionCookie, string? spn, ChannelBinding? channelBindingToken);
         string AuthenticationType { get; }
 
         //
index a3e0b88..f8bb106 100644 (file)
@@ -2,7 +2,6 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
-using System;
 using System.IO;
 using System.Net.Mime;
 using System.Text;
@@ -18,11 +17,11 @@ namespace System.Net.Mail
             base(fileName)
         { }
 
-        public LinkedResource(string fileName, string mediaType) :
+        public LinkedResource(string fileName, string? mediaType) :
             base(fileName, mediaType)
         { }
 
-        public LinkedResource(string fileName, ContentType contentType) :
+        public LinkedResource(string fileName, ContentType? contentType) :
             base(fileName, contentType)
         { }
 
@@ -30,15 +29,15 @@ namespace System.Net.Mail
             base(contentStream)
         { }
 
-        public LinkedResource(Stream contentStream, string mediaType) :
+        public LinkedResource(Stream contentStream, string? mediaType) :
             base(contentStream, mediaType)
         { }
 
-        public LinkedResource(Stream contentStream, ContentType contentType) :
+        public LinkedResource(Stream contentStream, ContentType? contentType) :
             base(contentStream, contentType)
         { }
 
-        public Uri ContentLink
+        public Uri? ContentLink
         {
             get
             {
@@ -58,14 +57,14 @@ namespace System.Net.Mail
             return a;
         }
 
-        public static LinkedResource CreateLinkedResourceFromString(string content, Encoding contentEncoding, string mediaType)
+        public static LinkedResource CreateLinkedResourceFromString(string content, Encoding? contentEncoding, string? mediaType)
         {
             LinkedResource a = new LinkedResource();
             a.SetContentFromString(content, contentEncoding, mediaType);
             return a;
         }
 
-        public static LinkedResource CreateLinkedResourceFromString(string content, ContentType contentType)
+        public static LinkedResource CreateLinkedResourceFromString(string content, ContentType? contentType)
         {
             LinkedResource a = new LinkedResource();
             a.SetContentFromString(content, contentType);
index 4f64c2a..9519b3f 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
 using System.Globalization;
 using System.Net.Mime;
 using System.Text;
@@ -24,7 +25,7 @@ namespace System.Net.Mail
 
         // For internal use only by MailAddressParser.
         // The components were already validated before this is called.
-        internal MailAddress(string displayName, string userName, string domain, Encoding displayNameEncoding)
+        internal MailAddress(string displayName, string userName, string domain, Encoding? displayNameEncoding)
         {
             _host = domain;
             _userName = userName;
@@ -41,11 +42,11 @@ namespace System.Net.Mail
                 "displayName was null in internal constructor");
         }
 
-        public MailAddress(string address) : this(address, null, (Encoding)null)
+        public MailAddress(string address) : this(address, null, (Encoding?)null)
         {
         }
 
-        public MailAddress(string address, string displayName) : this(address, displayName, (Encoding)null)
+        public MailAddress(string address, string? displayName) : this(address, displayName, (Encoding?)null)
         {
         }
 
@@ -62,7 +63,7 @@ namespace System.Net.Mail
         // field.  The display name does not need to be pre-encoded if a 'displayNameEncoding' is provided.
         //
         // A FormatException will be thrown if any of the components in 'address' are invalid.
-        public MailAddress(string address, string displayName, Encoding displayNameEncoding)
+        public MailAddress(string address, string? displayName, Encoding? displayNameEncoding)
         {
             bool parseSuccess = TryParse(address, displayName, displayNameEncoding,
                                         out (string displayName, string user, string host, Encoding displayNameEncoding) parsedData,
@@ -82,7 +83,7 @@ namespace System.Net.Mail
         /// <param name="address">A <see cref="string"/> that contains an email address.</param>
         /// <param name="result">When this method returns, contains the <see cref="MailAddress"/> instance if address parsing succeed</param>
         /// <returns>A <see cref="bool"/> value that is true if the <see cref="MailAddress"/> was successfully created; otherwise, false.</returns>
-        public static bool TryCreate(string address, out MailAddress result) => TryCreate(address, displayName: null, out result);
+        public static bool TryCreate(string address, [NotNullWhen(true)] out MailAddress? result) => TryCreate(address, displayName: null, out result);
 
         /// <summary>
         /// Create a new <see cref="MailAddress"/>. Does not throw an exception if the MailAddress cannot be created.
@@ -91,7 +92,7 @@ namespace System.Net.Mail
         /// <param name="displayName">A <see cref="string"/> that contains the display name associated with address. This parameter can be null.</param>
         /// <param name="result">When this method returns, contains the <see cref="MailAddress"/> instance if address parsing succeed</param>
         /// <returns>A <see cref="bool"/> value that is true if the <see cref="MailAddress"/> was successfully created; otherwise, false.</returns>
-        public static bool TryCreate(string address, string displayName, out MailAddress result) => TryCreate(address, displayName, displayNameEncoding: null, out result);
+        public static bool TryCreate(string address, string? displayName, [NotNullWhen(true)] out MailAddress? result) => TryCreate(address, displayName, displayNameEncoding: null, out result);
 
         /// <summary>
         /// Create a new <see cref="MailAddress"/>. Does not throw an exception if the MailAddress cannot be created.
@@ -101,7 +102,7 @@ namespace System.Net.Mail
         /// <param name="displayNameEncoding">The <see cref="Encoding"/> that defines the character set used for displayName</param>
         /// <param name="result">When this method returns, contains the <see cref="MailAddress"/> instance if address parsing succeed</param>
         /// <returns>A <see cref="bool"/> value that is true if the <see cref="MailAddress"/> was successfully created; otherwise, false.</returns>
-        public static bool TryCreate(string address, string displayName, Encoding displayNameEncoding, out MailAddress result)
+        public static bool TryCreate(string address, string? displayName, Encoding? displayNameEncoding, [NotNullWhen(true)] out MailAddress? result)
         {
             if (TryParse(address, displayName, displayNameEncoding,
                         out (string displayName, string user, string host, Encoding displayNameEncoding) parsed,
@@ -117,7 +118,7 @@ namespace System.Net.Mail
             }
         }
 
-        private static bool TryParse(string address, string displayName, Encoding displayNameEncoding, out (string displayName, string user, string host, Encoding displayNameEncoding) parsedData, bool throwExceptionIfFail)
+        private static bool TryParse(string address, string? displayName, Encoding? displayNameEncoding, out (string displayName, string user, string host, Encoding displayNameEncoding) parsedData, bool throwExceptionIfFail)
         {
             if (address == null)
             {
@@ -261,7 +262,7 @@ namespace System.Net.Mail
             }
         }
 
-        public override bool Equals(object value)
+        public override bool Equals(object? value)
         {
             if (value == null)
             {
index 2d51de5..358db8b 100644 (file)
@@ -81,7 +81,7 @@ namespace System.Net.Mail
             return headers;
         }
 
-        internal static string GetString(MailHeaderID id)
+        internal static string? GetString(MailHeaderID id)
         {
             switch (id)
             {
index ba8f742..83eddcd 100644 (file)
@@ -4,6 +4,7 @@
 
 using System;
 using System.Collections.Specialized;
+using System.Diagnostics.CodeAnalysis;
 using System.IO;
 using System.Net.Mime;
 using System.Text;
@@ -18,11 +19,11 @@ namespace System.Net.Mail
 
     public class MailMessage : IDisposable
     {
-        private AlternateViewCollection _views;
-        private AttachmentCollection _attachments;
-        private AlternateView _bodyView = null;
-        private string _body = string.Empty;
-        private Encoding _bodyEncoding;
+        private AlternateViewCollection? _views;
+        private AttachmentCollection? _attachments;
+        private AlternateView? _bodyView;
+        private string? _body = string.Empty;
+        private Encoding? _bodyEncoding;
         private TransferEncoding _bodyTransferEncoding = TransferEncoding.Unknown;
         private bool _isBodyHtml = false;
         private bool _disposed = false;
@@ -54,7 +55,7 @@ namespace System.Net.Mail
         }
 
 
-        public MailMessage(string from, string to, string subject, string body) : this(from, to)
+        public MailMessage(string from, string to, string? subject, string? body) : this(from, to)
         {
             Subject = subject;
             Body = body;
@@ -72,8 +73,8 @@ namespace System.Net.Mail
             _message = new Message(from, to);
         }
 
-
-        public MailAddress From
+        [DisallowNull]
+        public MailAddress? From
         {
             get
             {
@@ -89,7 +90,8 @@ namespace System.Net.Mail
             }
         }
 
-        public MailAddress Sender
+        [DisallowNull]
+        public MailAddress? Sender
         {
             get
             {
@@ -102,7 +104,7 @@ namespace System.Net.Mail
         }
 
         [Obsolete("ReplyTo is obsoleted for this type.  Please use ReplyToList instead which can accept multiple addresses. https://go.microsoft.com/fwlink/?linkid=14202")]
-        public MailAddress ReplyTo
+        public MailAddress? ReplyTo
         {
             get
             {
@@ -174,6 +176,7 @@ namespace System.Net.Mail
             }
         }
 
+        [AllowNull]
         public string Subject
         {
             get
@@ -186,7 +189,7 @@ namespace System.Net.Mail
             }
         }
 
-        public Encoding SubjectEncoding
+        public Encoding? SubjectEncoding
         {
             get
             {
@@ -206,7 +209,7 @@ namespace System.Net.Mail
             }
         }
 
-        public Encoding HeadersEncoding
+        public Encoding? HeadersEncoding
         {
             get
             {
@@ -218,6 +221,7 @@ namespace System.Net.Mail
             }
         }
 
+        [AllowNull]
         public string Body
         {
             get
@@ -243,7 +247,7 @@ namespace System.Net.Mail
             }
         }
 
-        public Encoding BodyEncoding
+        public Encoding? BodyEncoding
         {
             get
             {
@@ -290,11 +294,7 @@ namespace System.Net.Mail
                     throw new ObjectDisposedException(GetType().FullName);
                 }
 
-                if (_attachments == null)
-                {
-                    _attachments = new AttachmentCollection();
-                }
-                return _attachments;
+                return _attachments ??= new AttachmentCollection();
             }
         }
         public AlternateViewCollection AlternateViews
@@ -306,12 +306,7 @@ namespace System.Net.Mail
                     throw new ObjectDisposedException(GetType().FullName);
                 }
 
-                if (_views == null)
-                {
-                    _views = new AlternateViewCollection();
-                }
-
-                return _views;
+                return _views ??= new AlternateViewCollection();
             }
         }
 
@@ -389,7 +384,7 @@ namespace System.Net.Mail
             {
                 // we should not unnecessarily use Multipart/Mixed
                 // When there is no attachement and all the alternative views are of "Alternative" types.
-                MimeMultiPart part = null;
+                MimeMultiPart? part = null;
                 MimeMultiPart viewsPart = new MimeMultiPart(MimeMultiPartType.Alternative);
 
                 if (!string.IsNullOrEmpty(_body))
@@ -470,7 +465,7 @@ namespace System.Net.Mail
         }
 
         internal IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode,
-            AsyncCallback callback, object state)
+            AsyncCallback? callback, object? state)
         {
             SetContent(allowUnicode);
             return _message.BeginSend(writer, sendEnvelope, allowUnicode, callback, state);
index f4383d7..6c912e3 100644 (file)
@@ -2,6 +2,7 @@
 // The .NET Foundation licenses this file to you under the MIT license.
 // See the LICENSE file in the project root for more information.
 
+using System.Diagnostics.CodeAnalysis;
 using System.Net.Mime;
 using System.Runtime.ExceptionServices;
 using System.Text;
@@ -19,19 +20,19 @@ namespace System.Net.Mail
     {
         #region Fields
 
-        private MailAddress _from;
-        private MailAddress _sender;
-        private MailAddressCollection _replyToList;
-        private MailAddress _replyTo;
-        private MailAddressCollection _to;
-        private MailAddressCollection _cc;
-        private MailAddressCollection _bcc;
-        private MimeBasePart _content;
-        private HeaderCollection _headers;
-        private HeaderCollection _envelopeHeaders;
-        private string _subject;
-        private Encoding _subjectEncoding;
-        private Encoding _headersEncoding;
+        private MailAddress? _from;
+        private MailAddress? _sender;
+        private MailAddressCollection? _replyToList;
+        private MailAddress? _replyTo;
+        private MailAddressCollection? _to;
+        private MailAddressCollection? _cc;
+        private MailAddressCollection? _bcc;
+        private MimeBasePart? _content;
+        private HeaderCollection? _headers;
+        private HeaderCollection? _envelopeHeaders;
+        private string? _subject;
+        private Encoding? _subjectEncoding;
+        private Encoding? _headersEncoding;
         private MailPriority _priority = (MailPriority)(-1);
 
         #endregion Fields
@@ -85,7 +86,8 @@ namespace System.Net.Mail
             }
         }
 
-        internal MailAddress From
+        [DisallowNull]
+        internal MailAddress? From
         {
             get
             {
@@ -102,7 +104,7 @@ namespace System.Net.Mail
         }
 
 
-        internal MailAddress Sender
+        internal MailAddress? Sender
         {
             get
             {
@@ -115,7 +117,7 @@ namespace System.Net.Mail
         }
 
 
-        internal MailAddress ReplyTo
+        internal MailAddress? ReplyTo
         {
             get
             {
@@ -127,52 +129,16 @@ namespace System.Net.Mail
             }
         }
 
-        internal MailAddressCollection ReplyToList
-        {
-            get
-            {
-                if (_replyToList == null)
-                    _replyToList = new MailAddressCollection();
+        internal MailAddressCollection ReplyToList => _replyToList ??= new MailAddressCollection();
 
-                return _replyToList;
-            }
-        }
+        internal MailAddressCollection To => _to ??= new MailAddressCollection();
 
-        internal MailAddressCollection To
-        {
-            get
-            {
-                if (_to == null)
-                    _to = new MailAddressCollection();
+        internal MailAddressCollection Bcc => _bcc ??= new MailAddressCollection();
 
-                return _to;
-            }
-        }
+        internal MailAddressCollection CC => _cc ??= new MailAddressCollection();
 
-        internal MailAddressCollection Bcc
-        {
-            get
-            {
-                if (_bcc == null)
-                    _bcc = new MailAddressCollection();
 
-                return _bcc;
-            }
-        }
-
-        internal MailAddressCollection CC
-        {
-            get
-            {
-                if (_cc == null)
-                    _cc = new MailAddressCollection();
-
-                return _cc;
-            }
-        }
-
-
-        internal string Subject
+        internal string? Subject
         {
             get
             {
@@ -180,7 +146,7 @@ namespace System.Net.Mail
             }
             set
             {
-                Encoding inputEncoding = null;
+                Encoding? inputEncoding = null;
                 try
                 {
                     // extract the encoding from =?encoding?BorQ?blablalba?=
@@ -217,7 +183,7 @@ namespace System.Net.Mail
             }
         }
 
-        internal Encoding SubjectEncoding
+        internal Encoding? SubjectEncoding
         {
             get
             {
@@ -243,7 +209,7 @@ namespace System.Net.Mail
             }
         }
 
-        internal Encoding HeadersEncoding
+        internal Encoding? HeadersEncoding
         {
             get
             {
@@ -269,8 +235,8 @@ namespace System.Net.Mail
             }
         }
 
-
-        internal virtual MimeBasePart Content
+        [DisallowNull]
+        internal virtual MimeBasePart? Content
         {
             get
             {
@@ -293,14 +259,14 @@ namespace System.Net.Mail
 
         internal void EmptySendCallback(IAsyncResult result)
         {
-            Exception e = null;
+            Exception? e = null;
 
             if (result.CompletedSynchronously)
             {
                 return;
             }
 
-            EmptySendContext context = (EmptySendContext)result.AsyncState;
+            EmptySendContext context = (EmptySendContext)result.AsyncState!;
             try
             {
                 context._writer.EndGetContentStream(result).Close();
@@ -325,7 +291,7 @@ namespace System.Net.Mail
         }
 
         internal virtual IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode,
-            AsyncCallback callback, object state)
+            AsyncCallback? callback, object? state)
         {
             PrepareHeaders(sendEnvelope, allowUnicode);
             writer.WriteHeaders(Headers, allowUnicode);
@@ -360,7 +326,7 @@ namespace System.Net.Mail
             }
             else
             {
-                LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult;
+                LazyAsyncResult? castedAsyncResult = asyncResult as LazyAsyncResult;
 
                 if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
                 {
@@ -412,14 +378,14 @@ namespace System.Net.Mail
             EncodeHeaders(EnvelopeHeaders, allowUnicode);
 
             // Only add X-Sender header if it wasn't already set by the user
-            string xSenderHeader = MailHeaderInfo.GetString(MailHeaderID.XSender);
+            string xSenderHeader = MailHeaderInfo.GetString(MailHeaderID.XSender)!;
             if (!IsHeaderSet(xSenderHeader))
             {
-                MailAddress sender = Sender ?? From;
+                MailAddress sender = Sender ?? From!;
                 EnvelopeHeaders.InternalSet(xSenderHeader, sender.Encode(xSenderHeader.Length, allowUnicode));
             }
 
-            string headerName = MailHeaderInfo.GetString(MailHeaderID.XReceiver);
+            string headerName = MailHeaderInfo.GetString(MailHeaderID.XReceiver)!;
             EnvelopeHeaders.Remove(headerName);
 
             foreach (MailAddress address in To)
@@ -446,13 +412,13 @@ namespace System.Net.Mail
             }
 
             //ContentType is written directly to the stream so remove potential user duplicate
-            Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType));
+            Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType)!);
 
             Headers[MailHeaderInfo.GetString(MailHeaderID.MimeVersion)] = "1.0";
 
             // add sender to headers first so that it is written first to allow the IIS smtp svc to
             // send MAIL FROM with the sender if both sender and from are present
-            headerName = MailHeaderInfo.GetString(MailHeaderID.Sender);
+            headerName = MailHeaderInfo.GetString(MailHeaderID.Sender)!;
             if (Sender != null)
             {
                 Headers.InternalAdd(headerName, Sender.Encode(headerName.Length, allowUnicode));
@@ -462,10 +428,10 @@ namespace System.Net.Mail
                 Headers.Remove(headerName);
             }
 
-            headerName = MailHeaderInfo.GetString(MailHeaderID.From);
-            Headers.InternalAdd(headerName, From.Encode(headerName.Length, allowUnicode));
+            headerName = MailHeaderInfo.GetString(MailHeaderID.From)!;
+            Headers.InternalAdd(headerName, From!.Encode(headerName.Length, allowUnicode));
 
-            headerName = MailHeaderInfo.GetString(MailHeaderID.To);
+            headerName = MailHeaderInfo.GetString(MailHeaderID.To)!;
             if (To.Count > 0)
             {
                 Headers.InternalAdd(headerName, To.Encode(headerName.Length, allowUnicode));
@@ -475,7 +441,7 @@ namespace System.Net.Mail
                 Headers.Remove(headerName);
             }
 
-            headerName = MailHeaderInfo.GetString(MailHeaderID.Cc);
+            headerName = MailHeaderInfo.GetString(MailHeaderID.Cc)!;
             if (CC.Count > 0)
             {
                 Headers.InternalAdd(headerName, CC.Encode(headerName.Length, allowUnicode));
@@ -485,7 +451,7 @@ namespace System.Net.Mail
                 Headers.Remove(headerName);
             }
 
-            headerName = MailHeaderInfo.GetString(MailHeaderID.ReplyTo);
+            headerName = MailHeaderInfo.GetString(MailHeaderID.ReplyTo)!;
             if (ReplyTo != null)
             {
                 Headers.InternalAdd(headerName, ReplyTo.Encode(headerName.Length, allowUnicode));
@@ -499,7 +465,7 @@ namespace System.Net.Mail
                 Headers.Remove(headerName);
             }
 
-            Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Bcc));
+            Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Bcc)!);
 
             if (_priority == MailPriority.High)
             {
@@ -516,15 +482,15 @@ namespace System.Net.Mail
             //if the priority was never set, allow the app to set the headers directly.
             else if (((int)_priority) != -1)
             {
-                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.XPriority));
-                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Priority));
-                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Importance));
+                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.XPriority)!);
+                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Priority)!);
+                Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Importance)!);
             }
 
-            Headers.InternalAdd(MailHeaderInfo.GetString(MailHeaderID.Date),
-                MailBnfHelper.GetDateTimeString(DateTime.Now, null));
+            Headers.InternalAdd(MailHeaderInfo.GetString(MailHeaderID.Date)!,
+                MailBnfHelper.GetDateTimeString(DateTime.Now, null)!);
 
-            headerName = MailHeaderInfo.GetString(MailHeaderID.Subject);
+            headerName = MailHeaderInfo.GetString(MailHeaderID.Subject)!;
             if (!string.IsNullOrEmpty(_subject))
             {
                 if (allowUnicode)
@@ -544,21 +510,18 @@ namespace System.Net.Mail
                 Headers.Remove(headerName);
             }
 
-            EncodeHeaders(_headers, allowUnicode);
+            EncodeHeaders(_headers!, allowUnicode);
         }
 
         internal void EncodeHeaders(HeaderCollection headers, bool allowUnicode)
         {
-            if (_headersEncoding == null)
-            {
-                _headersEncoding = Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
-            }
+            _headersEncoding ??= Encoding.GetEncoding(MimeBasePart.DefaultCharSet);
 
             System.Diagnostics.Debug.Assert(_headersEncoding != null);
 
             for (int i = 0; i < headers.Count; i++)
             {
-                string headerName = headers.GetKey(i);
+                string headerName = headers.GetKey(i)!;
 
                 //certain well-known values are encoded by PrepareHeaders and PrepareEnvelopeHeaders
                 //so we can ignore them because either we encoded them already or there is no
@@ -569,7 +532,7 @@ namespace System.Net.Mail
                     continue;
                 }
 
-                string[] values = headers.GetValues(headerName);
+                string[] values = headers.GetValues(headerName)!;
                 string encodedValue = string.Empty;
                 for (int j = 0; j < values.Length; j++)
                 {
@@ -605,7 +568,7 @@ namespace System.Net.Mail
             }
         }
 
-        private bool IsHeaderSet(string headerName)
+        private bool IsHeaderSet(string? headerName)
         {
             for (int i = 0; i < Headers.Count; i++)
             {
index 8a827af..ddd4b21 100644 (file)
@@ -28,11 +28,11 @@ namespace System.Net.Mail
             if (headers == null)
                 throw new ArgumentNullException(nameof(headers));
 
-            foreach (string key in headers)
+            foreach (string? key in headers) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/3214
             {
-                string[] values = headers.GetValues(key);
+                string[] values = headers!.GetValues(key)!;
                 foreach (string value in values)
-                    WriteHeader(key, value, allowUnicode);
+                    WriteHeader(key!, value, allowUnicode);
             }
         }
 
@@ -52,11 +52,11 @@ namespace System.Net.Mail
         /// </summary>
         /// <param name="sender">Sender of the close event</param>
         /// <param name="args">Event args (not used)</param>
-        protected override void OnClose(object sender, EventArgs args)
+        protected override void OnClose(object? sender, EventArgs args)
         {
             Diagnostics.Debug.Assert(_contentStream == sender);
             _contentStream.Flush();
-            _contentStream = null;
+            _contentStream = null!;
         }
     }
 }
index 5ae9dc9..834b5ba 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.ComponentModel;
+using System.Diagnostics.CodeAnalysis;
 using System.Globalization;
 using System.IO;
 using System.Net.NetworkInformation;
@@ -33,36 +34,36 @@ namespace System.Net.Mail
 
     public class SmtpClient : IDisposable
     {
-        private string _host;
+        private string? _host;
         private int _port;
         private int _timeout = 100000;
         private bool _inCall;
         private bool _cancelled;
         private bool _timedOut;
-        private string _targetName = null;
+        private string? _targetName;
         private SmtpDeliveryMethod _deliveryMethod = SmtpDeliveryMethod.Network;
         private SmtpDeliveryFormat _deliveryFormat = SmtpDeliveryFormat.SevenBit; // Non-EAI default
-        private string _pickupDirectoryLocation = null;
-        private SmtpTransport _transport;
-        private MailMessage _message; //required to prevent premature finalization
-        private MailWriter _writer;
-        private MailAddressCollection _recipients;
-        private SendOrPostCallback _onSendCompletedDelegate;
-        private Timer _timer;
-        private ContextAwareResult _operationCompletedResult = null;
-        private AsyncOperation _asyncOp = null;
+        private string? _pickupDirectoryLocation;
+        private SmtpTransport _transport = null!; // initialized by helper called from ctor
+        private MailMessage? _message; //required to prevent premature finalization
+        private MailWriter? _writer;
+        private MailAddressCollection? _recipients;
+        private SendOrPostCallback _onSendCompletedDelegate = null!; // initialized by helper called from ctor
+        private Timer? _timer;
+        private ContextAwareResult? _operationCompletedResult;
+        private AsyncOperation? _asyncOp;
         private static readonly AsyncCallback s_contextSafeCompleteCallback = new AsyncCallback(ContextSafeCompleteCallback);
         private const int DefaultPort = 25;
-        internal string clientDomain = null;
-        private bool _disposed = false;
-        private ServicePoint _servicePoint;
+        internal string _clientDomain = null!; // initialized by helper called from ctor
+        private bool _disposed;
+        private ServicePoint? _servicePoint;
         // (async only) For when only some recipients fail.  We still send the e-mail to the others.
-        private SmtpFailedRecipientException _failedRecipientException;
+        private SmtpFailedRecipientException? _failedRecipientException;
         // ports above this limit are invalid
         private const int MaxPortValue = 65535;
-        public event SendCompletedEventHandler SendCompleted;
+        public event SendCompletedEventHandler? SendCompleted;
         private bool _useDefaultCredentials;
-        private ICredentialsByHost _customCredentials;
+        private ICredentialsByHost? _customCredentials;
 
         public SmtpClient()
         {
@@ -77,7 +78,7 @@ namespace System.Net.Mail
             }
         }
 
-        public SmtpClient(string host)
+        public SmtpClient(string? host)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host);
             try
@@ -91,7 +92,7 @@ namespace System.Net.Mail
             }
         }
 
-        public SmtpClient(string host, int port)
+        public SmtpClient(string? host, int port)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, host, port);
             try
@@ -130,7 +131,7 @@ namespace System.Net.Mail
             if (_targetName == null)
                 _targetName = "SMTPSVC/" + _host;
 
-            if (clientDomain == null)
+            if (_clientDomain == null)
             {
                 // We use the local host name as the default client domain
                 // for the client's EHLO or HELO message. This limits the
@@ -161,14 +162,14 @@ namespace System.Net.Mail
                         sb.Append(ch);
                 }
                 if (sb.Length > 0)
-                    clientDomain = sb.ToString();
+                    _clientDomain = sb.ToString();
                 else
-                    clientDomain = "LocalHost";
+                    _clientDomain = "LocalHost";
             }
         }
 
-
-        public string Host
+        [DisallowNull]
+        public string? Host
         {
             get
             {
@@ -245,7 +246,7 @@ namespace System.Net.Mail
             }
         }
 
-        public ICredentialsByHost Credentials
+        public ICredentialsByHost? Credentials
         {
             get
             {
@@ -295,17 +296,14 @@ namespace System.Net.Mail
             get
             {
                 CheckHostAndPort();
-                if (_servicePoint == null)
-                {
-                    // This differs from desktop, where it uses an internal overload of FindServicePoint that just
-                    // takes a string host and an int port, bypassing the need for a Uri. We workaround that here by
-                    // creating an http Uri, simply for the purposes of getting an appropriate ServicePoint instance.
-                    // This has some subtle impact on behavior, e.g. the returned ServicePoint's Address property will
-                    // be usable, whereas in .NET Framework it throws an exception that "This property is not supported for
-                    // protocols that do not use URI."
-                    _servicePoint = ServicePointManager.FindServicePoint(new Uri("mailto:" + _host + ":" + _port));
-                }
-                return _servicePoint;
+
+                // This differs from desktop, where it uses an internal overload of FindServicePoint that just
+                // takes a string host and an int port, bypassing the need for a Uri. We workaround that here by
+                // creating an http Uri, simply for the purposes of getting an appropriate ServicePoint instance.
+                // This has some subtle impact on behavior, e.g. the returned ServicePoint's Address property will
+                // be usable, whereas in .NET Framework it throws an exception that "This property is not supported for
+                // protocols that do not use URI."
+                return _servicePoint ??= ServicePointManager.FindServicePoint(new Uri("mailto:" + _host + ":" + _port));
             }
         }
 
@@ -333,7 +331,7 @@ namespace System.Net.Mail
             }
         }
 
-        public string PickupDirectoryLocation
+        public string? PickupDirectoryLocation
         {
             get
             {
@@ -371,7 +369,7 @@ namespace System.Net.Mail
             }
         }
 
-        public string TargetName
+        public string? TargetName
         {
             get { return _targetName; }
             set { _targetName = value; }
@@ -397,7 +395,7 @@ namespace System.Net.Mail
             }
         }
 
-        internal MailWriter GetFileMailWriter(string pickupDirectory)
+        internal MailWriter GetFileMailWriter(string? pickupDirectory)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"{nameof(pickupDirectory)}={pickupDirectory}");
 
@@ -422,12 +420,12 @@ namespace System.Net.Mail
             SendCompleted?.Invoke(this, e);
         }
 
-        private void SendCompletedWaitCallback(object operationState)
+        private void SendCompletedWaitCallback(object? operationState)
         {
-            OnSendCompleted((AsyncCompletedEventArgs)operationState);
+            OnSendCompleted((AsyncCompletedEventArgs)operationState!);
         }
 
-        public void Send(string from, string recipients, string subject, string body)
+        public void Send(string from, string recipients, string? subject, string? body)
         {
             if (_disposed)
             {
@@ -454,7 +452,7 @@ namespace System.Net.Mail
                     NetEventSource.Associate(this, message);
                 }
 
-                SmtpFailedRecipientException recipientException = null;
+                SmtpFailedRecipientException? recipientException = null;
 
                 if (InCall)
                 {
@@ -511,7 +509,7 @@ namespace System.Net.Mail
                     _timedOut = false;
                     _timer = new Timer(new TimerCallback(TimeOutCallback), null, Timeout, Timeout);
                     bool allowUnicode = false;
-                    string pickupDirectory = PickupDirectoryLocation;
+                    string? pickupDirectory = PickupDirectoryLocation;
 
                     MailWriter writer;
                     switch (DeliveryMethod)
@@ -589,7 +587,7 @@ namespace System.Net.Mail
             }
         }
 
-        public void SendAsync(string from, string recipients, string subject, string body, object userToken)
+        public void SendAsync(string from, string recipients, string? subject, string? body, object? userToken)
         {
             if (_disposed)
             {
@@ -598,7 +596,7 @@ namespace System.Net.Mail
             SendAsync(new MailMessage(from, recipients, subject, body), userToken);
         }
 
-        public void SendAsync(MailMessage message, object userToken)
+        public void SendAsync(MailMessage message, object? userToken)
         {
             if (_disposed)
             {
@@ -661,9 +659,9 @@ namespace System.Net.Mail
                     InCall = true;
                     _cancelled = false;
                     _message = message;
-                    string pickupDirectory = PickupDirectoryLocation;
+                    string? pickupDirectory = PickupDirectoryLocation;
 
-                    CredentialCache cache;
+                    CredentialCache? cache;
                     // Skip token capturing if no credentials are used or they don't include a default one.
                     // Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be.
                     _transport.IdentityRequired = Credentials != null && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));
@@ -701,7 +699,7 @@ namespace System.Net.Mail
                             lock (_operationCompletedResult.StartPostingAsyncOp())
                             {
                                 if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
-                                _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host, Port);
+                                _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host!, Port);
                                 _operationCompletedResult.FinishPostingAsyncOp();
                             }
                             break;
@@ -739,7 +737,7 @@ namespace System.Net.Mail
         private bool IsSystemNetworkCredentialInCache(CredentialCache cache)
         {
             // Check if SystemNetworkCredential is in given cache.
-            foreach (NetworkCredential credential in cache)
+            foreach (NetworkCredential? credential in cache) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/3214
             {
                 if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
                 {
@@ -777,7 +775,7 @@ namespace System.Net.Mail
 
 
         //************* Task-based async public methods *************************
-        public Task SendMailAsync(string from, string recipients, string subject, string body)
+        public Task SendMailAsync(string from, string recipients, string? subject, string? body)
         {
             var message = new MailMessage(from, recipients, subject, body);
             return SendMailAsync(message, cancellationToken: default);
@@ -788,7 +786,7 @@ namespace System.Net.Mail
             return SendMailAsync(message, cancellationToken: default);
         }
 
-        public Task SendMailAsync(string from, string recipients, string subject, string body, CancellationToken cancellationToken)
+        public Task SendMailAsync(string from, string recipients, string? subject, string? body, CancellationToken cancellationToken)
         {
             var message = new MailMessage(from, recipients, subject, body);
             return SendMailAsync(message, cancellationToken);
@@ -802,7 +800,7 @@ namespace System.Net.Mail
             }
 
             // Create a TaskCompletionSource to represent the operation
-            var tcs = new TaskCompletionSource<object>();
+            var tcs = new TaskCompletionSource<object?>();
 
             CancellationTokenRegistration ctr = default;
 
@@ -810,7 +808,7 @@ namespace System.Net.Mail
             int state = 0;
 
             // Register a handler that will transfer completion results to the TCS Task
-            SendCompletedEventHandler handler = null;
+            SendCompletedEventHandler? handler = null;
             handler = (sender, e) =>
             {
                 if (e.UserState == tcs)
@@ -848,7 +846,7 @@ namespace System.Net.Mail
 
             ctr = cancellationToken.Register(s =>
             {
-                ((SmtpClient)s).SendAsyncCancel();
+                ((SmtpClient)s!).SendAsyncCancel();
             }, this);
 
             if (Interlocked.Exchange(ref state, 1) != 0)
@@ -889,7 +887,7 @@ namespace System.Net.Mail
             }
         }
 
-        private void TimeOutCallback(object state)
+        private void TimeOutCallback(object? state)
         {
             if (!_timedOut)
             {
@@ -898,9 +896,9 @@ namespace System.Net.Mail
             }
         }
 
-        private void Complete(Exception exception, IAsyncResult result)
+        private void Complete(Exception? exception, IAsyncResult result)
         {
-            ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState;
+            ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState!;
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
             try
             {
@@ -948,9 +946,9 @@ namespace System.Net.Mail
         private static void ContextSafeCompleteCallback(IAsyncResult ar)
         {
             ContextAwareResult result = (ContextAwareResult)ar;
-            SmtpClient client = (SmtpClient)ar.AsyncState;
-            Exception exception = result.Result as Exception;
-            AsyncOperation asyncOp = client._asyncOp;
+            SmtpClient client = (SmtpClient)ar.AsyncState!;
+            Exception? exception = result.Result as Exception;
+            AsyncOperation asyncOp = client._asyncOp!;
             AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(exception, client._cancelled, asyncOp.UserSuppliedState);
             client.InCall = false;
             client._failedRecipientException = null; // Reset before the next send.
@@ -962,7 +960,7 @@ namespace System.Net.Mail
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
             try
             {
-                _message.EndSend(result);
+                _message!.EndSend(result);
                 // If some recipients failed but not others, throw AFTER sending the message.
                 Complete(_failedRecipientException, result);
             }
@@ -1005,8 +1003,8 @@ namespace System.Net.Mail
                 }
                 else
                 {
-                    _message.BeginSend(_writer, DeliveryMethod != SmtpDeliveryMethod.Network,
-                        IsUnicodeSupported(), new AsyncCallback(SendMessageCallback), result.AsyncState);
+                    _message!.BeginSend(_writer, DeliveryMethod != SmtpDeliveryMethod.Network,
+                        IsUnicodeSupported(), new AsyncCallback(SendMessageCallback), result.AsyncState!);
                 }
             }
             catch (Exception e)
@@ -1033,10 +1031,10 @@ namespace System.Net.Mail
                 {
                     // Detected durring Begin/EndGetConnection, restrictable using DeliveryFormat
                     bool allowUnicode = IsUnicodeSupported();
-                    ValidateUnicodeRequirement(_message, _recipients, allowUnicode);
-                    _transport.BeginSendMail(_message.Sender ?? _message.From, _recipients,
+                    ValidateUnicodeRequirement(_message!, _recipients!, allowUnicode);
+                    _transport.BeginSendMail(_message!.Sender ?? _message.From!, _recipients!,
                         _message.BuildDeliveryStatusNotificationString(), allowUnicode,
-                        new AsyncCallback(SendMailCallback), result.AsyncState);
+                        new AsyncCallback(SendMailCallback), result.AsyncState!);
                 }
             }
             catch (Exception e)
@@ -1060,18 +1058,16 @@ namespace System.Net.Mail
             {
                 address.GetSmtpAddress(allowUnicode);
             }
-            if (message.Sender != null)
-            {
-                message.Sender.GetSmtpAddress(allowUnicode);
-            }
-            message.From.GetSmtpAddress(allowUnicode);
+
+            message.Sender?.GetSmtpAddress(allowUnicode);
+            message.From!.GetSmtpAddress(allowUnicode);
         }
 
         private void GetConnection()
         {
             if (!_transport.IsConnected)
             {
-                _transport.GetConnection(_host, _port);
+                _transport.GetConnection(_host!, _port);
             }
         }
 
index 36fd589..7966452 100644 (file)
@@ -17,7 +17,7 @@ namespace System.Net.Mail
         private static readonly AsyncCallback s_onReadLine = new AsyncCallback(OnReadLine);
         private static readonly AsyncCallback s_onWrite = new AsyncCallback(OnWrite);
 
-        internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
+        internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback? callback, object? state)
         {
             MultiAsyncResult multiResult = new MultiAsyncResult(conn, callback, state);
             multiResult.Enter();
@@ -27,7 +27,7 @@ namespace System.Net.Mail
                 conn.EndFlush(writeResult);
                 multiResult.Leave();
             }
-            SmtpReplyReader reader = conn.Reader.GetNextReplyReader();
+            SmtpReplyReader reader = conn.Reader!.GetNextReplyReader();
             multiResult.Enter();
 
             //this actually does a read on the stream.
@@ -46,7 +46,7 @@ namespace System.Net.Mail
 
         internal static object EndSend(IAsyncResult result, out string response)
         {
-            object commandResult = MultiAsyncResult.End(result);
+            object commandResult = MultiAsyncResult.End(result)!;
             if (commandResult is Exception e)
             {
                 ExceptionDispatchInfo.Throw(e);
@@ -61,11 +61,11 @@ namespace System.Net.Mail
         {
             if (!result.CompletedSynchronously)
             {
-                MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
+                MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState!;
                 try
                 {
                     SmtpConnection conn = (SmtpConnection)multiResult.Context;
-                    LineInfo info = conn.Reader.CurrentReader.EndReadLine(result);
+                    LineInfo info = conn.Reader!.CurrentReader!.EndReadLine(result);
                     if (!(multiResult.Result is Exception))
                         multiResult.Result = info;
                     multiResult.Leave();
@@ -81,7 +81,7 @@ namespace System.Net.Mail
         {
             if (!result.CompletedSynchronously)
             {
-                MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
+                MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState!;
                 try
                 {
                     SmtpConnection conn = (SmtpConnection)multiResult.Context;
@@ -98,7 +98,7 @@ namespace System.Net.Mail
         internal static SmtpStatusCode Send(SmtpConnection conn, out string response)
         {
             conn.Flush();
-            SmtpReplyReader reader = conn.Reader.GetNextReplyReader();
+            SmtpReplyReader reader = conn.Reader!.GetNextReplyReader();
             LineInfo info = reader.ReadLine();
             response = info.Line;
             reader.Close();
@@ -111,7 +111,7 @@ namespace System.Net.Mail
         private static readonly AsyncCallback s_onReadLines = new AsyncCallback(OnReadLines);
         private static readonly AsyncCallback s_onWrite = new AsyncCallback(OnWrite);
 
-        internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
+        internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback? callback, object? state)
         {
             MultiAsyncResult multiResult = new MultiAsyncResult(conn, callback, state);
             multiResult.Enter();
@@ -121,12 +121,12 @@ namespace System.Net.Mail
                 conn.EndFlush(writeResult);
                 multiResult.Leave();
             }
-            SmtpReplyReader reader = conn.Reader.GetNextReplyReader();
+            SmtpReplyReader reader = conn.Reader!.GetNextReplyReader();
             multiResult.Enter();
             IAsyncResult readLinesResult = reader.BeginReadLines(s_onReadLines, multiResult);
             if (readLinesResult.CompletedSynchronously)
             {
-                LineInfo[] lines = conn.Reader.CurrentReader.EndReadLines(readLinesResult);
+                LineInfo[] lines = conn.Reader.CurrentReader!.EndReadLines(readLinesResult);
                 if (!(multiResult.Result is Exception))
                     multiResult.Result = lines;
                 multiResult.Leave();
@@ -137,7 +137,7 @@ namespace System.Net.Mail
 
         internal static LineInfo[] EndSend(IAsyncResult result)
         {
-            object commandResult = MultiAsyncResult.End(result);
+            object commandResult = MultiAsyncResult.End(result)!;
             if (commandResult is Exception e)
             {
                 ExceptionDispatchInfo.Throw(e);
@@ -149,11 +149,11 @@ namespace System.Net.Mail
         {
             if (!result.CompletedSynchronously)
             {
-                MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
+                MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState!;
                 try
                 {
                     SmtpConnection conn = (SmtpConnection)multiResult.Context;
-                    LineInfo[] lines = conn.Reader.CurrentReader.EndReadLines(result);
+                    LineInfo[] lines = conn.Reader!.CurrentReader!.EndReadLines(result);
                     if (!(multiResult.Result is Exception))
                         multiResult.Result = lines;
                     multiResult.Leave();
@@ -169,7 +169,7 @@ namespace System.Net.Mail
         {
             if (!result.CompletedSynchronously)
             {
-                MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
+                MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState!;
                 try
                 {
                     SmtpConnection conn = (SmtpConnection)multiResult.Context;
@@ -185,19 +185,19 @@ namespace System.Net.Mail
         internal static LineInfo[] Send(SmtpConnection conn)
         {
             conn.Flush();
-            return conn.Reader.GetNextReplyReader().ReadLines();
+            return conn.Reader!.GetNextReplyReader().ReadLines();
         }
     }
 
     internal static class AuthCommand
     {
-        internal static IAsyncResult BeginSend(SmtpConnection conn, string type, string message, AsyncCallback callback, object state)
+        internal static IAsyncResult BeginSend(SmtpConnection conn, string type, string message, AsyncCallback? callback, object? state)
         {
             PrepareCommand(conn, type, message);
             return ReadLinesCommand.BeginSend(conn, callback, state);
         }
 
-        internal static IAsyncResult BeginSend(SmtpConnection conn, string message, AsyncCallback callback, object state)
+        internal static IAsyncResult BeginSend(SmtpConnection conn, string? message, AsyncCallback? callback, object? state)
         {
             PrepareCommand(conn, message);
             return ReadLinesCommand.BeginSend(conn, callback, state);
@@ -226,7 +226,7 @@ namespace System.Net.Mail
             conn.BufferBuilder.Append(SmtpCommands.CRLF);
         }
 
-        private static void PrepareCommand(SmtpConnection conn, string message)
+        private static void PrepareCommand(SmtpConnection conn, string? message)
         {
             conn.BufferBuilder.Append(message);
             conn.BufferBuilder.Append(SmtpCommands.CRLF);
@@ -238,7 +238,7 @@ namespace System.Net.Mail
             return CheckResponse(ReadLinesCommand.Send(conn));
         }
 
-        internal static LineInfo Send(SmtpConnection conn, string message)
+        internal static LineInfo Send(SmtpConnection conn, string? message)
         {
             PrepareCommand(conn, message);
             return CheckResponse(ReadLinesCommand.Send(conn));
@@ -247,7 +247,7 @@ namespace System.Net.Mail
 
     internal static class DataCommand
     {
-        internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
+        internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback? callback, object? state)
         {
             PrepareCommand(conn);
             return CheckCommand.BeginSend(conn, callback, state);
@@ -347,7 +347,7 @@ namespace System.Net.Mail
 
     internal static class EHelloCommand
     {
-        internal static IAsyncResult BeginSend(SmtpConnection conn, string domain, AsyncCallback callback, object state)
+        internal static IAsyncResult BeginSend(SmtpConnection conn, string domain, AsyncCallback? callback, object? state)
         {
             PrepareCommand(conn, domain);
             return ReadLinesCommand.BeginSend(conn, callback, state);
@@ -401,7 +401,7 @@ namespace System.Net.Mail
 
     internal static class HelloCommand
     {
-        internal static IAsyncResult BeginSend(SmtpConnection conn, string domain, AsyncCallback callback, object state)
+        internal static IAsyncResult BeginSend(SmtpConnection conn, string domain, AsyncCallback? callback, object? state)
         {
             PrepareCommand(conn, domain);
             return CheckCommand.BeginSend(conn, callback, state);
@@ -457,7 +457,7 @@ namespace System.Net.Mail
 
     internal static class StartTlsCommand
     {
-        internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback callback, object state)
+        internal static IAsyncResult BeginSend(SmtpConnection conn, AsyncCallback? callback, object? state)
         {
             PrepareCommand(conn);
             return CheckCommand.BeginSend(conn, callback, state);
@@ -515,7 +515,7 @@ namespace System.Net.Mail
     internal static class MailCommand
     {
         internal static IAsyncResult BeginSend(SmtpConnection conn, byte[] command, MailAddress from,
-            bool allowUnicode, AsyncCallback callback, object state)
+            bool allowUnicode, AsyncCallback? callback, object? state)
         {
             PrepareCommand(conn, command, from, allowUnicode);
             return CheckCommand.BeginSend(conn, callback, state);
@@ -578,7 +578,7 @@ namespace System.Net.Mail
 
     internal static class RecipientCommand
     {
-        internal static IAsyncResult BeginSend(SmtpConnection conn, string to, AsyncCallback callback, object state)
+        internal static IAsyncResult BeginSend(SmtpConnection conn, string to, AsyncCallback? callback, object? state)
         {
             PrepareCommand(conn, to);
             return CheckCommand.BeginSend(conn, callback, state);
index 12852ea..54855af 100644 (file)
@@ -26,22 +26,20 @@ namespace System.Net.Mail
         private bool _isConnected;
         private bool _isClosed;
         private bool _isStreamOpen;
-        private readonly EventHandler _onCloseHandler;
-        internal SmtpTransport _parent;
-        private readonly SmtpClient _client;
-        private NetworkStream _networkStream;
-        internal TcpClient _tcpClient;
-        internal string _host = null;
+        private readonly EventHandler? _onCloseHandler;
+        internal SmtpTransport? _parent;
+        private readonly SmtpClient? _client;
+        private NetworkStream? _networkStream;
+        internal TcpClient? _tcpClient;
         internal int _port = 0;
-        private SmtpReplyReaderFactory _responseReader;
+        private SmtpReplyReaderFactory? _responseReader;
 
-        private readonly ICredentialsByHost _credentials;
-        private string[] _extensions;
-        private readonly ChannelBinding _channelBindingToken = null;
+        private readonly ICredentialsByHost? _credentials;
+        private string[]? _extensions;
         private bool _enableSsl;
-        private X509CertificateCollection _clientCertificates;
+        private X509CertificateCollection? _clientCertificates;
 
-        internal SmtpConnection(SmtpTransport parent, SmtpClient client, ICredentialsByHost credentials, ISmtpAuthenticationModule[] authenticationModules)
+        internal SmtpConnection(SmtpTransport parent, SmtpClient client, ICredentialsByHost? credentials, ISmtpAuthenticationModule[] authenticationModules)
         {
             _client = client;
             _credentials = credentials;
@@ -57,7 +55,7 @@ namespace System.Net.Mail
 
         internal bool IsStreamOpen => _isStreamOpen;
 
-        internal SmtpReplyReaderFactory Reader => _responseReader;
+        internal SmtpReplyReaderFactory? Reader => _responseReader;
 
         internal bool EnableSsl
         {
@@ -71,7 +69,7 @@ namespace System.Net.Mail
             }
         }
 
-        internal X509CertificateCollection ClientCertificates
+        internal X509CertificateCollection? ClientCertificates
         {
             get
             {
@@ -85,42 +83,42 @@ namespace System.Net.Mail
 
         internal void InitializeConnection(string host, int port)
         {
-            _tcpClient.Connect(host, port);
+            _tcpClient!.Connect(host, port);
             _networkStream = _tcpClient.GetStream();
         }
 
-        internal IAsyncResult BeginInitializeConnection(string host, int port, AsyncCallback callback, object state)
+        internal IAsyncResult BeginInitializeConnection(string host, int port, AsyncCallback? callback, object? state)
         {
-            return _tcpClient.BeginConnect(host, port, callback, state);
+            return _tcpClient!.BeginConnect(host, port, callback, state);
         }
 
         internal void EndInitializeConnection(IAsyncResult result)
         {
-            _tcpClient.EndConnect(result);
+            _tcpClient!.EndConnect(result);
             _networkStream = _tcpClient.GetStream();
         }
 
-        internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port)
+        internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback? callback, object? state, string host, int port)
         {
             ConnectAndHandshakeAsyncResult result = new ConnectAndHandshakeAsyncResult(this, host, port, outerResult, callback, state);
             result.GetConnection();
             return result;
         }
 
-        internal IAsyncResult BeginFlush(AsyncCallback callback, object state)
+        internal IAsyncResult BeginFlush(AsyncCallback? callback, object? state)
         {
-            return _networkStream.BeginWrite(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length, callback, state);
+            return _networkStream!.BeginWrite(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length, callback, state);
         }
 
         internal void EndFlush(IAsyncResult result)
         {
-            _networkStream.EndWrite(result);
+            _networkStream!.EndWrite(result);
             _bufferBuilder.Reset();
         }
 
         internal void Flush()
         {
-            _networkStream.Write(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length);
+            _networkStream!.Write(_bufferBuilder.GetBuffer(), 0, _bufferBuilder.Length);
             _bufferBuilder.Reset();
         }
 
@@ -154,7 +152,6 @@ namespace System.Net.Mail
                             finally
                             {
                                 //free cbt buffer
-                                _channelBindingToken?.Close();
                                 _networkStream?.Close();
                                 _tcpClient.Dispose();
                             }
@@ -195,7 +192,7 @@ namespace System.Net.Mail
             }
 
             InitializeConnection(host, port);
-            _responseReader = new SmtpReplyReaderFactory(_networkStream);
+            _responseReader = new SmtpReplyReaderFactory(_networkStream!);
 
             LineInfo info = _responseReader.GetNextReplyReader().ReadLine();
 
@@ -209,7 +206,7 @@ namespace System.Net.Mail
 
             try
             {
-                _extensions = EHelloCommand.Send(this, _client.clientDomain);
+                _extensions = EHelloCommand.Send(this, _client!._clientDomain);
                 ParseExtensions(_extensions);
             }
             catch (SmtpException e)
@@ -220,7 +217,7 @@ namespace System.Net.Mail
                     throw;
                 }
 
-                HelloCommand.Send(this, _client.clientDomain);
+                HelloCommand.Send(this, _client!._clientDomain);
                 //if ehello isn't supported, assume basic login
                 _supportedAuth = SupportedAuth.Login;
             }
@@ -237,14 +234,14 @@ namespace System.Net.Mail
                 }
 
                 StartTlsCommand.Send(this);
-                TlsStream tlsStream = new TlsStream(_networkStream, _tcpClient.Client, host, _clientCertificates);
+                TlsStream tlsStream = new TlsStream(_networkStream!, _tcpClient!.Client, host, _clientCertificates);
                 tlsStream.AuthenticateAsClient();
                 _networkStream = tlsStream;
                 _responseReader = new SmtpReplyReaderFactory(_networkStream);
 
                 // According to RFC 3207: The client SHOULD send an EHLO command
                 // as the first command after a successful TLS negotiation.
-                _extensions = EHelloCommand.Send(this, _client.clientDomain);
+                _extensions = EHelloCommand.Send(this, _client._clientDomain);
                 ParseExtensions(_extensions);
             }
 
@@ -260,11 +257,11 @@ namespace System.Net.Mail
                         continue;
                     }
 
-                    NetworkCredential credential = _credentials.GetCredential(host, port, _authenticationModules[i].AuthenticationType);
+                    NetworkCredential? credential = _credentials.GetCredential(host, port, _authenticationModules[i].AuthenticationType);
                     if (credential == null)
                         continue;
 
-                    Authorization auth = SetContextAndTryAuthenticate(_authenticationModules[i], credential, null);
+                    Authorization? auth = SetContextAndTryAuthenticate(_authenticationModules[i], credential, null);
 
                     if (auth != null && auth.Message != null)
                     {
@@ -277,7 +274,7 @@ namespace System.Net.Mail
 
                         while ((int)info.StatusCode == 334)
                         {
-                            auth = _authenticationModules[i].Authenticate(info.Line, null, this, _client.TargetName, _channelBindingToken);
+                            auth = _authenticationModules[i].Authenticate(info.Line, null, this, _client.TargetName, null);
                             if (auth == null)
                             {
                                 throw new SmtpException(SR.SmtpAuthenticationFailed);
@@ -298,7 +295,7 @@ namespace System.Net.Mail
             _isConnected = true;
         }
 
-        private Authorization SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential credential, ContextAwareResult context)
+        private Authorization? SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential? credential, ContextAwareResult? context)
         {
             // We may need to restore user thread token here
             if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
@@ -312,18 +309,18 @@ namespace System.Net.Mail
 
                 try
                 {
-                    ExecutionContext x = context == null ? null : context.ContextCopy;
+                    ExecutionContext? x = context == null ? null : context.ContextCopy;
                     if (x != null)
                     {
                         AuthenticateCallbackContext authenticationContext =
-                            new AuthenticateCallbackContext(this, module, credential, _client.TargetName, _channelBindingToken);
+                            new AuthenticateCallbackContext(this, module, credential, _client!.TargetName, null);
 
                         ExecutionContext.Run(x, s_AuthenticateCallback, authenticationContext);
                         return authenticationContext._result;
                     }
                     else
                     {
-                        return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken);
+                        return module.Authenticate(null, credential, this, _client!.TargetName, null);
                     }
                 }
                 catch
@@ -333,18 +330,18 @@ namespace System.Net.Mail
                 }
             }
 
-            return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken);
+            return module.Authenticate(null, credential, this, _client!.TargetName, null);
         }
 
-        private static void AuthenticateCallback(object state)
+        private static void AuthenticateCallback(object? state)
         {
-            AuthenticateCallbackContext context = (AuthenticateCallbackContext)state;
+            AuthenticateCallbackContext context = (AuthenticateCallbackContext)state!;
             context._result = context._module.Authenticate(null, context._credential, context._thisPtr, context._spn, context._token);
         }
 
         private class AuthenticateCallbackContext
         {
-            internal AuthenticateCallbackContext(SmtpConnection thisPtr, ISmtpAuthenticationModule module, NetworkCredential credential, string spn, ChannelBinding Token)
+            internal AuthenticateCallbackContext(SmtpConnection thisPtr, ISmtpAuthenticationModule module, NetworkCredential credential, string? spn, ChannelBinding? Token)
             {
                 _thisPtr = thisPtr;
                 _module = module;
@@ -358,10 +355,10 @@ namespace System.Net.Mail
             internal readonly SmtpConnection _thisPtr;
             internal readonly ISmtpAuthenticationModule _module;
             internal readonly NetworkCredential _credential;
-            internal readonly string _spn;
-            internal readonly ChannelBinding _token;
+            internal readonly string? _spn;
+            internal readonly ChannelBinding? _token;
 
-            internal Authorization _result;
+            internal Authorization? _result;
         }
 
         internal void EndGetConnection(IAsyncResult result)
@@ -371,12 +368,12 @@ namespace System.Net.Mail
 
         internal Stream GetClosableStream()
         {
-            ClosableStream cs = new ClosableStream(_networkStream, _onCloseHandler);
+            ClosableStream cs = new ClosableStream(_networkStream!, _onCloseHandler);
             _isStreamOpen = true;
             return cs;
         }
 
-        private void OnClose(object sender, EventArgs args)
+        private void OnClose(object? sender, EventArgs args)
         {
             _isStreamOpen = false;
 
@@ -385,7 +382,7 @@ namespace System.Net.Mail
 
         private class ConnectAndHandshakeAsyncResult : LazyAsyncResult
         {
-            private string _authResponse;
+            private string? _authResponse;
             private readonly SmtpConnection _connection;
             private int _currentModule = -1;
             private readonly int _port;
@@ -399,7 +396,7 @@ namespace System.Net.Mail
             private readonly ContextAwareResult _outerResult;
 
 
-            internal ConnectAndHandshakeAsyncResult(SmtpConnection connection, string host, int port, ContextAwareResult outerResult, AsyncCallback callback, object state) :
+            internal ConnectAndHandshakeAsyncResult(SmtpConnection connection, string host, int port, ContextAwareResult outerResult, AsyncCallback? callback, object? state) :
                 base(null, state, callback)
             {
                 _connection = connection;
@@ -412,7 +409,7 @@ namespace System.Net.Mail
             internal static void End(IAsyncResult result)
             {
                 ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result;
-                object connectResult = thisPtr.InternalWaitForCompletion();
+                object? connectResult = thisPtr.InternalWaitForCompletion();
                 if (connectResult is Exception e)
                 {
                     ExceptionDispatchInfo.Throw(e);
@@ -453,7 +450,7 @@ namespace System.Net.Mail
             {
                 if (!result.CompletedSynchronously)
                 {
-                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
                     try
                     {
                         thisPtr._connection.EndInitializeConnection(result);
@@ -470,9 +467,9 @@ namespace System.Net.Mail
 
             private void Handshake()
             {
-                _connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream);
+                _connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream!);
 
-                SmtpReplyReader reader = _connection.Reader.GetNextReplyReader();
+                SmtpReplyReader reader = _connection.Reader!.GetNextReplyReader();
                 IAsyncResult result = reader.BeginReadLine(s_handshakeCallback, this);
                 if (!result.CompletedSynchronously)
                 {
@@ -505,12 +502,12 @@ namespace System.Net.Mail
             {
                 if (!result.CompletedSynchronously)
                 {
-                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
                     try
                     {
                         try
                         {
-                            LineInfo info = thisPtr._connection.Reader.CurrentReader.EndReadLine(result);
+                            LineInfo info = thisPtr._connection.Reader!.CurrentReader!.EndReadLine(result);
                             if (info.StatusCode != SmtpStatusCode.ServiceReady)
                             {
                                 thisPtr.InvokeCallback(new SmtpException(info.StatusCode, info.Line, true));
@@ -538,7 +535,7 @@ namespace System.Net.Mail
 
             private bool SendEHello()
             {
-                IAsyncResult result = EHelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendEHelloCallback, this);
+                IAsyncResult result = EHelloCommand.BeginSend(_connection, _connection._client!._clientDomain, s_sendEHelloCallback, this);
                 if (result.CompletedSynchronously)
                 {
                     _connection._extensions = EHelloCommand.EndSend(result);
@@ -578,7 +575,7 @@ namespace System.Net.Mail
             {
                 if (!result.CompletedSynchronously)
                 {
-                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
                     try
                     {
                         try
@@ -638,7 +635,7 @@ namespace System.Net.Mail
 
             private bool SendHello()
             {
-                IAsyncResult result = HelloCommand.BeginSend(_connection, _connection._client.clientDomain, s_sendHelloCallback, this);
+                IAsyncResult result = HelloCommand.BeginSend(_connection, _connection._client!._clientDomain, s_sendHelloCallback, this);
                 //if ehello isn't supported, assume basic auth
                 if (result.CompletedSynchronously)
                 {
@@ -654,7 +651,7 @@ namespace System.Net.Mail
             {
                 if (!result.CompletedSynchronously)
                 {
-                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
                     try
                     {
                         HelloCommand.EndSend(result);
@@ -683,7 +680,7 @@ namespace System.Net.Mail
             {
                 if (!result.CompletedSynchronously)
                 {
-                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
                     try
                     {
                         StartTlsCommand.EndSend(result);
@@ -698,11 +695,11 @@ namespace System.Net.Mail
 
             private bool TlsStreamAuthenticate()
             {
-                _connection._networkStream = new TlsStream(_connection._networkStream, _connection._tcpClient.Client, _host, _connection._clientCertificates);
-                IAsyncResult result = (_connection._networkStream as TlsStream).BeginAuthenticateAsClient(TlsStreamAuthenticateCallback, this);
+                _connection._networkStream = new TlsStream(_connection._networkStream!, _connection._tcpClient!.Client, _host, _connection._clientCertificates);
+                IAsyncResult result = ((TlsStream)_connection._networkStream).BeginAuthenticateAsClient(TlsStreamAuthenticateCallback, this);
                 if (result.CompletedSynchronously)
                 {
-                    (_connection._networkStream as TlsStream).EndAuthenticateAsClient(result);
+                    ((TlsStream)_connection._networkStream).EndAuthenticateAsClient(result);
                     _connection._responseReader = new SmtpReplyReaderFactory(_connection._networkStream);
                     SendEHello();
                     return true;
@@ -714,10 +711,10 @@ namespace System.Net.Mail
             {
                 if (!result.CompletedSynchronously)
                 {
-                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
                     try
                     {
-                        (thisPtr._connection._networkStream as TlsStream).EndAuthenticateAsClient(result);
+                        (thisPtr._connection._networkStream as TlsStream)!.EndAuthenticateAsClient(result);
                         thisPtr._connection._responseReader = new SmtpReplyReaderFactory(thisPtr._connection._networkStream);
                         thisPtr.SendEHello();
                     }
@@ -743,10 +740,10 @@ namespace System.Net.Mail
                             continue;
                         }
 
-                        NetworkCredential credential = _connection._credentials.GetCredential(_host, _port, module.AuthenticationType);
+                        NetworkCredential? credential = _connection._credentials.GetCredential(_host, _port, module.AuthenticationType);
                         if (credential == null)
                             continue;
-                        Authorization auth = _connection.SetContextAndTryAuthenticate(module, credential, _outerResult);
+                        Authorization? auth = _connection.SetContextAndTryAuthenticate(module, credential, _outerResult);
 
                         if (auth != null && auth.Message != null)
                         {
@@ -784,7 +781,7 @@ namespace System.Net.Mail
             {
                 if (!result.CompletedSynchronously)
                 {
-                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
                     try
                     {
                         LineInfo info = AuthCommand.EndSend(result);
@@ -820,7 +817,7 @@ namespace System.Net.Mail
                 {
                     // We don't need credential on the continued auth assuming they were captured on the first call.
                     // That should always work, otherwise what if a new credential has been returned?
-                    Authorization auth = _connection._authenticationModules[_currentModule].Authenticate(_authResponse, null, _connection, _connection._client.TargetName, _connection._channelBindingToken);
+                    Authorization? auth = _connection._authenticationModules[_currentModule].Authenticate(_authResponse, null, _connection, _connection._client!.TargetName, null);
                     if (auth == null)
                     {
                         throw new SmtpException(SR.SmtpAuthenticationFailed);
@@ -852,7 +849,7 @@ namespace System.Net.Mail
             {
                 if (!result.CompletedSynchronously)
                 {
-                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState;
+                    ConnectAndHandshakeAsyncResult thisPtr = (ConnectAndHandshakeAsyncResult)result.AsyncState!;
                     try
                     {
                         LineInfo info = AuthCommand.EndSend(result);
index 1eca3a8..8183cb1 100644 (file)
@@ -12,7 +12,7 @@ namespace System.Net.Mail
     {
         private SmtpStatusCode _statusCode = SmtpStatusCode.GeneralFailure;
 
-        private static string GetMessageForStatus(SmtpStatusCode statusCode, string serverResponse)
+        private static string GetMessageForStatus(SmtpStatusCode statusCode, string? serverResponse)
         {
             return GetMessageForStatus(statusCode) + " " + SR.Format(SR.MailServerResponse, serverResponse);
         }
@@ -76,7 +76,7 @@ namespace System.Net.Mail
             _statusCode = statusCode;
         }
 
-        public SmtpException(SmtpStatusCode statusCode, string message) : base(message)
+        public SmtpException(SmtpStatusCode statusCode, string? message) : base(message)
         {
             _statusCode = statusCode;
         }
@@ -85,11 +85,11 @@ namespace System.Net.Mail
         {
         }
 
-        public SmtpException(string message) : base(message)
+        public SmtpException(string? message) : base(message)
         {
         }
 
-        public SmtpException(string message, Exception innerException) : base(message, innerException)
+        public SmtpException(string? message, Exception? innerException) : base(message, innerException)
         {
         }
 
@@ -98,12 +98,12 @@ namespace System.Net.Mail
             _statusCode = (SmtpStatusCode)serializationInfo.GetInt32("Status");
         }
 
-        internal SmtpException(SmtpStatusCode statusCode, string serverMessage, bool serverResponse) : base(GetMessageForStatus(statusCode, serverMessage))
+        internal SmtpException(SmtpStatusCode statusCode, string? serverMessage, bool serverResponse) : base(GetMessageForStatus(statusCode, serverMessage))
         {
             _statusCode = statusCode;
         }
 
-        internal SmtpException(string message, string serverResponse) : base(message + " " + SR.Format(SR.MailServerResponse, serverResponse))
+        internal SmtpException(string message, string? serverResponse) : base(message + " " + SR.Format(SR.MailServerResponse, serverResponse))
         {
         }
 
index bad12ea..2f20761 100644 (file)
@@ -12,36 +12,36 @@ namespace System.Net.Mail
     [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
     public class SmtpFailedRecipientException : SmtpException, ISerializable
     {
-        private readonly string _failedRecipient;
+        private readonly string? _failedRecipient;
         internal bool fatal;
 
         public SmtpFailedRecipientException() : base() { }
 
-        public SmtpFailedRecipientException(string message) : base(message) { }
+        public SmtpFailedRecipientException(string? message) : base(message) { }
 
-        public SmtpFailedRecipientException(string message, Exception innerException) : base(message, innerException) { }
+        public SmtpFailedRecipientException(string? message, Exception? innerException) : base(message, innerException) { }
 
         protected SmtpFailedRecipientException(SerializationInfo info, StreamingContext context) : base(info, context)
         {
             _failedRecipient = info.GetString("failedRecipient");
         }
 
-        public SmtpFailedRecipientException(SmtpStatusCode statusCode, string failedRecipient) : base(statusCode)
+        public SmtpFailedRecipientException(SmtpStatusCode statusCode, string? failedRecipient) : base(statusCode)
         {
             _failedRecipient = failedRecipient;
         }
 
-        public SmtpFailedRecipientException(SmtpStatusCode statusCode, string failedRecipient, string serverResponse) : base(statusCode, serverResponse, true)
+        public SmtpFailedRecipientException(SmtpStatusCode statusCode, string? failedRecipient, string? serverResponse) : base(statusCode, serverResponse, true)
         {
             _failedRecipient = failedRecipient;
         }
 
-        public SmtpFailedRecipientException(string message, string failedRecipient, Exception innerException) : base(message, innerException)
+        public SmtpFailedRecipientException(string? message, string? failedRecipient, Exception? innerException) : base(message, innerException)
         {
             _failedRecipient = failedRecipient;
         }
 
-        public string FailedRecipient
+        public string? FailedRecipient
         {
             get
             {
index e6a3b38..00bbff5 100644 (file)
@@ -19,23 +19,23 @@ namespace System.Net.Mail
             _innerExceptions = Array.Empty<SmtpFailedRecipientException>();
         }
 
-        public SmtpFailedRecipientsException(string message) : base(message)
+        public SmtpFailedRecipientsException(string? message) : base(message)
         {
             _innerExceptions = Array.Empty<SmtpFailedRecipientException>();
         }
 
-        public SmtpFailedRecipientsException(string message, Exception innerException) : base(message, innerException)
+        public SmtpFailedRecipientsException(string? message, Exception? innerException) : base(message, innerException)
         {
-            SmtpFailedRecipientException smtpException = innerException as SmtpFailedRecipientException;
+            SmtpFailedRecipientException? smtpException = innerException as SmtpFailedRecipientException;
             _innerExceptions = smtpException == null ? Array.Empty<SmtpFailedRecipientException>() : new SmtpFailedRecipientException[] { smtpException };
         }
 
         protected SmtpFailedRecipientsException(SerializationInfo info, StreamingContext context) : base(info, context)
         {
-            _innerExceptions = (SmtpFailedRecipientException[])info.GetValue("innerExceptions", typeof(SmtpFailedRecipientException[]));
+            _innerExceptions = (SmtpFailedRecipientException[])info.GetValue("innerExceptions", typeof(SmtpFailedRecipientException[]))!;
         }
 
-        public SmtpFailedRecipientsException(string message, SmtpFailedRecipientException[] innerExceptions) :
+        public SmtpFailedRecipientsException(string? message, SmtpFailedRecipientException[] innerExceptions) :
             base(message, innerExceptions != null && innerExceptions.Length > 0 ? innerExceptions[0].FailedRecipient : null,
             innerExceptions != null && innerExceptions.Length > 0 ? innerExceptions[0] : null)
         {
index 11fe637..3d9f335 100644 (file)
@@ -15,14 +15,14 @@ namespace System.Net.Mail
         {
         }
 
-        public Authorization Authenticate(string challenge, NetworkCredential credential, object sessionCookie, string spn, ChannelBinding channelBindingToken)
+        public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
             try
             {
                 lock (_sessions)
                 {
-                    NetworkCredential cachedCredential;
+                    NetworkCredential? cachedCredential;
                     if (!_sessions.TryGetValue(sessionCookie, out cachedCredential))
                     {
                         if (credential == null || ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
index 854ea63..b0e216c 100644 (file)
@@ -16,14 +16,14 @@ namespace System.Net.Mail
         {
         }
 
-        public Authorization Authenticate(string challenge, NetworkCredential credential, object sessionCookie, string spn, ChannelBinding channelBindingToken)
+        public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, "Authenticate");
             try
             {
                 lock (_sessions)
                 {
-                    NTAuthentication clientContext;
+                    NTAuthentication? clientContext;
                     if (!_sessions.TryGetValue(sessionCookie, out clientContext))
                     {
                         if (credential == null)
@@ -37,8 +37,8 @@ namespace System.Net.Mail
                                                  ContextFlagsPal.Connection | ContextFlagsPal.InitIntegrity, channelBindingToken);
                     }
 
-                    byte[] byteResp;
-                    string resp = null;
+                    byte[]? byteResp;
+                    string? resp = null;
 
                     if (!clientContext.IsCompleted)
                     {
@@ -46,7 +46,7 @@ namespace System.Net.Mail
                         // If auth is not yet completed keep producing
                         // challenge responses with GetOutgoingBlob
 
-                        byte[] decodedChallenge = null;
+                        byte[]? decodedChallenge = null;
                         if (challenge != null)
                         {
                             decodedChallenge =
@@ -96,7 +96,7 @@ namespace System.Net.Mail
 
         public void CloseContext(object sessionCookie)
         {
-            NTAuthentication clientContext = null;
+            NTAuthentication? clientContext = null;
             lock (_sessions)
             {
                 if (_sessions.TryGetValue(sessionCookie, out clientContext))
@@ -115,7 +115,7 @@ namespace System.Net.Mail
         //
         // Returns null for failure, Base64 encoded string on
         // success.
-        private string GetSecurityLayerOutgoingBlob(string challenge, NTAuthentication clientContext)
+        private string? GetSecurityLayerOutgoingBlob(string? challenge, NTAuthentication clientContext)
         {
             // must have a security layer challenge
 
@@ -182,7 +182,7 @@ namespace System.Net.Mail
             // "authorization identity" is not supplied as it is unnecessary.
 
             // let MakeSignature figure out length of output
-            byte[] output = null;
+            byte[]? output = null;
             try
             {
                 len = clientContext.MakeSignature(input, 0, 4, ref output);
index c811702..b24080b 100644 (file)
@@ -15,14 +15,14 @@ namespace System.Net.Mail
         {
         }
 
-        public Authorization Authenticate(string challenge, NetworkCredential credential, object sessionCookie, string spn, ChannelBinding channelBindingToken)
+        public Authorization? Authenticate(string? challenge, NetworkCredential? credential, object sessionCookie, string? spn, ChannelBinding? channelBindingToken)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this, "Authenticate");
             try
             {
                 lock (_sessions)
                 {
-                    NTAuthentication clientContext;
+                    NTAuthentication? clientContext;
                     if (!_sessions.TryGetValue(sessionCookie, out clientContext))
                     {
                         if (credential == null)
@@ -36,7 +36,7 @@ namespace System.Net.Mail
 
                     }
 
-                    string resp = clientContext.GetOutgoingBlob(challenge);
+                    string? resp = clientContext.GetOutgoingBlob(challenge);
 
                     if (!clientContext.IsCompleted)
                     {
index 5105ef1..6f86a11 100644 (file)
@@ -17,12 +17,12 @@ namespace System.Net.Mail
             _reader = reader;
         }
 
-        internal IAsyncResult BeginReadLines(AsyncCallback callback, object state)
+        internal IAsyncResult BeginReadLines(AsyncCallback? callback, object? state)
         {
             return _reader.BeginReadLines(this, callback, state);
         }
 
-        internal IAsyncResult BeginReadLine(AsyncCallback callback, object state)
+        internal IAsyncResult BeginReadLine(AsyncCallback? callback, object? state)
         {
             return _reader.BeginReadLine(this, callback, state);
         }
index 833a5f8..627353f 100644 (file)
@@ -27,8 +27,8 @@ namespace System.Net.Mail
         }
 
         private readonly BufferedReadStream _bufferedStream;
-        private byte[] _byteBuffer;
-        private SmtpReplyReader _currentReader;
+        private byte[]? _byteBuffer;
+        private SmtpReplyReader? _currentReader;
         private const int DefaultBufferSize = 256;
         private ReadState _readState = ReadState.Status0;
         private SmtpStatusCode _statusCode;
@@ -38,7 +38,7 @@ namespace System.Net.Mail
             _bufferedStream = new BufferedReadStream(stream);
         }
 
-        internal SmtpReplyReader CurrentReader
+        internal SmtpReplyReader? CurrentReader
         {
             get
             {
@@ -54,14 +54,14 @@ namespace System.Net.Mail
             }
         }
 
-        internal IAsyncResult BeginReadLines(SmtpReplyReader caller, AsyncCallback callback, object state)
+        internal IAsyncResult BeginReadLines(SmtpReplyReader caller, AsyncCallback? callback, object? state)
         {
             ReadLinesAsyncResult result = new ReadLinesAsyncResult(this, callback, state);
             result.Read(caller);
             return result;
         }
 
-        internal IAsyncResult BeginReadLine(SmtpReplyReader caller, AsyncCallback callback, object state)
+        internal IAsyncResult BeginReadLine(SmtpReplyReader caller, AsyncCallback? callback, object? state)
         {
             ReadLinesAsyncResult result = new ReadLinesAsyncResult(this, callback, state, true);
             result.Read(caller);
@@ -370,20 +370,20 @@ namespace System.Net.Mail
 
         private class ReadLinesAsyncResult : LazyAsyncResult
         {
-            private StringBuilder _builder;
-            private ArrayList _lines;
+            private StringBuilder? _builder;
+            private ArrayList? _lines;
             private readonly SmtpReplyReaderFactory _parent;
             private static readonly AsyncCallback s_readCallback = new AsyncCallback(ReadCallback);
             private int _read;
             private int _statusRead;
             private readonly bool _oneLine;
 
-            internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback callback, object state) : base(null, state, callback)
+            internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback? callback, object? state) : base(null, state, callback)
             {
                 _parent = parent;
             }
 
-            internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback callback, object state, bool oneLine) : base(null, state, callback)
+            internal ReadLinesAsyncResult(SmtpReplyReaderFactory parent, AsyncCallback? callback, object? state, bool oneLine) : base(null, state, callback)
             {
                 _oneLine = oneLine;
                 _parent = parent;
@@ -416,14 +416,14 @@ namespace System.Net.Mail
             {
                 ReadLinesAsyncResult thisPtr = (ReadLinesAsyncResult)result;
                 thisPtr.InternalWaitForCompletion();
-                return (LineInfo[])thisPtr._lines.ToArray(typeof(LineInfo));
+                return (LineInfo[])thisPtr._lines!.ToArray(typeof(LineInfo));
             }
 
             private void Read()
             {
                 do
                 {
-                    IAsyncResult result = _parent._bufferedStream.BeginRead(_parent._byteBuffer, 0, _parent._byteBuffer.Length, s_readCallback, this);
+                    IAsyncResult result = _parent._bufferedStream.BeginRead(_parent._byteBuffer!, 0, _parent._byteBuffer!.Length, s_readCallback, this);
                     if (!result.CompletedSynchronously)
                     {
                         return;
@@ -436,8 +436,8 @@ namespace System.Net.Mail
             {
                 if (!result.CompletedSynchronously)
                 {
-                    Exception exception = null;
-                    ReadLinesAsyncResult thisPtr = (ReadLinesAsyncResult)result.AsyncState;
+                    Exception? exception = null;
+                    ReadLinesAsyncResult thisPtr = (ReadLinesAsyncResult)result.AsyncState!;
                     try
                     {
                         thisPtr._read = thisPtr._parent._bufferedStream.EndRead(result);
@@ -467,7 +467,7 @@ namespace System.Net.Mail
 
                 for (int start = 0; start != _read;)
                 {
-                    int actual = _parent.ProcessRead(_parent._byteBuffer, start, _read - start, true);
+                    int actual = _parent.ProcessRead(_parent._byteBuffer!, start, _read - start, true);
 
                     if (_statusRead < 4)
                     {
@@ -481,26 +481,26 @@ namespace System.Net.Mail
                         }
                     }
 
-                    _builder.Append(Encoding.UTF8.GetString(_parent._byteBuffer, start, actual));
+                    _builder!.Append(Encoding.UTF8.GetString(_parent._byteBuffer!, start, actual));
                     start += actual;
 
                     if (_parent._readState == ReadState.Status0)
                     {
-                        _lines.Add(new LineInfo(_parent._statusCode, _builder.ToString(0, _builder.Length - 2))); // return everything except CRLF
+                        _lines!.Add(new LineInfo(_parent._statusCode, _builder.ToString(0, _builder.Length - 2))); // return everything except CRLF
                         _builder = new StringBuilder();
                         _statusRead = 0;
 
                         if (_oneLine)
                         {
-                            _parent._bufferedStream.Push(_parent._byteBuffer, start, _read - start);
+                            _parent._bufferedStream.Push(_parent._byteBuffer!, start, _read - start);
                             InvokeCallback();
                             return false;
                         }
                     }
                     else if (_parent._readState == ReadState.Done)
                     {
-                        _lines.Add(new LineInfo(_parent._statusCode, _builder.ToString(0, _builder.Length - 2))); // return everything except CRLF
-                        _parent._bufferedStream.Push(_parent._byteBuffer, start, _read - start);
+                        _lines!.Add(new LineInfo(_parent._statusCode, _builder.ToString(0, _builder.Length - 2))); // return everything except CRLF
+                        _parent._bufferedStream.Push(_parent._byteBuffer!, start, _read - start);
                         InvokeCallback();
                         return false;
                     }
index 281a00c..32e0bbd 100644 (file)
@@ -16,15 +16,15 @@ namespace System.Net.Mail
         internal const int DefaultPort = 25;
 
         private readonly ISmtpAuthenticationModule[] _authenticationModules;
-        private SmtpConnection _connection;
+        private SmtpConnection? _connection;
         private readonly SmtpClient _client;
-        private ICredentialsByHost _credentials;
+        private ICredentialsByHost? _credentials;
         private readonly List<SmtpFailedRecipientException> _failedRecipientExceptions = new List<SmtpFailedRecipientException>();
         private bool _identityRequired;
         private bool _shouldAbort;
 
         private bool _enableSsl = false;
-        private X509CertificateCollection _clientCertificates = null;
+        private X509CertificateCollection? _clientCertificates;
 
         internal SmtpTransport(SmtpClient client) : this(client, SmtpAuthenticationManager.GetModules())
         {
@@ -42,7 +42,7 @@ namespace System.Net.Mail
             _authenticationModules = authenticationModules;
         }
 
-        internal ICredentialsByHost Credentials
+        internal ICredentialsByHost? Credentials
         {
             get
             {
@@ -87,17 +87,7 @@ namespace System.Net.Mail
             }
         }
 
-        internal X509CertificateCollection ClientCertificates
-        {
-            get
-            {
-                if (_clientCertificates == null)
-                {
-                    _clientCertificates = new X509CertificateCollection();
-                }
-                return _clientCertificates;
-            }
-        }
+        internal X509CertificateCollection ClientCertificates => _clientCertificates ??= new X509CertificateCollection();
 
         internal bool ServerSupportsEai
         {
@@ -131,10 +121,10 @@ namespace System.Net.Mail
             finally { }
         }
 
-        internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port)
+        internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback? callback, object? state, string host, int port)
         {
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
-            IAsyncResult result = null;
+            IAsyncResult? result = null;
             try
             {
                 _connection = new SmtpConnection(this, _client, _credentials, _authenticationModules);
@@ -165,7 +155,7 @@ namespace System.Net.Mail
             if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
             try
             {
-                _connection.EndGetConnection(result);
+                _connection!.EndGetConnection(result);
             }
             finally
             {
@@ -174,7 +164,7 @@ namespace System.Net.Mail
         }
 
         internal IAsyncResult BeginSendMail(MailAddress sender, MailAddressCollection recipients,
-            string deliveryNotify, bool allowUnicode, AsyncCallback callback, object state)
+            string deliveryNotify, bool allowUnicode, AsyncCallback? callback, object? state)
         {
             if (sender == null)
             {
@@ -186,8 +176,8 @@ namespace System.Net.Mail
                 throw new ArgumentNullException(nameof(recipients));
             }
 
-            SendMailAsyncResult result = new SendMailAsyncResult(_connection, sender, recipients,
-                allowUnicode, _connection.DSNEnabled ? deliveryNotify : null,
+            SendMailAsyncResult result = new SendMailAsyncResult(_connection!, sender, recipients,
+                allowUnicode, _connection!.DSNEnabled ? deliveryNotify : null,
                 callback, state);
             result.Send();
             return result;
@@ -225,7 +215,7 @@ namespace System.Net.Mail
         }
 
         internal MailWriter SendMail(MailAddress sender, MailAddressCollection recipients, string deliveryNotify,
-            bool allowUnicode, out SmtpFailedRecipientException exception)
+            bool allowUnicode, out SmtpFailedRecipientException? exception)
         {
             if (sender == null)
             {
@@ -237,7 +227,7 @@ namespace System.Net.Mail
                 throw new ArgumentNullException(nameof(recipients));
             }
 
-            MailCommand.Send(_connection, SmtpCommands.Mail, sender, allowUnicode);
+            MailCommand.Send(_connection!, SmtpCommands.Mail, sender, allowUnicode);
             _failedRecipientExceptions.Clear();
 
             exception = null;
@@ -245,11 +235,11 @@ namespace System.Net.Mail
             foreach (MailAddress address in recipients)
             {
                 string smtpAddress = address.GetSmtpAddress(allowUnicode);
-                string to = smtpAddress + (_connection.DSNEnabled ? deliveryNotify : string.Empty);
+                string to = smtpAddress + (_connection!.DSNEnabled ? deliveryNotify : string.Empty);
                 if (!RecipientCommand.Send(_connection, to, out response))
                 {
                     _failedRecipientExceptions.Add(
-                        new SmtpFailedRecipientException(_connection.Reader.StatusCode, smtpAddress, response));
+                        new SmtpFailedRecipientException(_connection.Reader!.StatusCode, smtpAddress, response));
                 }
             }
 
@@ -271,8 +261,8 @@ namespace System.Net.Mail
                 }
             }
 
-            DataCommand.Send(_connection);
-            return new MailWriter(_connection.GetClosableStream(), encodeForTransport: true);
+            DataCommand.Send(_connection!);
+            return new MailWriter(_connection!.GetClosableStream(), encodeForTransport: true);
         }
     }
 
@@ -280,19 +270,19 @@ namespace System.Net.Mail
     {
         private readonly SmtpConnection _connection;
         private readonly MailAddress _from;
-        private readonly string _deliveryNotify;
+        private readonly string? _deliveryNotify;
         private static readonly AsyncCallback s_sendMailFromCompleted = new AsyncCallback(SendMailFromCompleted);
         private static readonly AsyncCallback s_sendToCollectionCompleted = new AsyncCallback(SendToCollectionCompleted);
         private static readonly AsyncCallback s_sendDataCompleted = new AsyncCallback(SendDataCompleted);
         private readonly List<SmtpFailedRecipientException> _failedRecipientExceptions = new List<SmtpFailedRecipientException>();
-        private Stream _stream;
+        private Stream? _stream;
         private readonly MailAddressCollection _toCollection;
         private int _toIndex;
         private readonly bool _allowUnicode;
 
 
         internal SendMailAsyncResult(SmtpConnection connection, MailAddress from, MailAddressCollection toCollection,
-            bool allowUnicode, string deliveryNotify, AsyncCallback callback, object state)
+            bool allowUnicode, string? deliveryNotify, AsyncCallback? callback, object? state)
             : base(null, state, callback)
         {
             _toCollection = toCollection;
@@ -310,7 +300,7 @@ namespace System.Net.Mail
         internal static MailWriter End(IAsyncResult result)
         {
             SendMailAsyncResult thisPtr = (SendMailAsyncResult)result;
-            object sendMailResult = thisPtr.InternalWaitForCompletion();
+            object? sendMailResult = thisPtr.InternalWaitForCompletion();
 
             // Note the difference between the singular and plural FailedRecipient exceptions.
             // Only fail immediately if we couldn't send to any recipients.
@@ -321,7 +311,7 @@ namespace System.Net.Mail
                 ExceptionDispatchInfo.Throw(e);
             }
 
-            return new MailWriter(thisPtr._stream, encodeForTransport: true);
+            return new MailWriter(thisPtr._stream!, encodeForTransport: true);
         }
         private void SendMailFrom()
         {
@@ -340,7 +330,7 @@ namespace System.Net.Mail
         {
             if (!result.CompletedSynchronously)
             {
-                SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState;
+                SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState!;
                 try
                 {
                     MailCommand.EndSend(result);
@@ -367,7 +357,7 @@ namespace System.Net.Mail
                 string response;
                 if (!RecipientCommand.EndSend(result, out response))
                 {
-                    _failedRecipientExceptions.Add(new SmtpFailedRecipientException(_connection.Reader.StatusCode,
+                    _failedRecipientExceptions.Add(new SmtpFailedRecipientException(_connection.Reader!.StatusCode,
                         _toCollection[_toIndex - 1].GetSmtpAddress(_allowUnicode), response));
                 }
             }
@@ -378,28 +368,22 @@ namespace System.Net.Mail
         {
             if (!result.CompletedSynchronously)
             {
-                SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState;
+                SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState!;
                 try
                 {
                     string response;
                     if (!RecipientCommand.EndSend(result, out response))
                     {
                         thisPtr._failedRecipientExceptions.Add(
-                            new SmtpFailedRecipientException(thisPtr._connection.Reader.StatusCode,
+                            new SmtpFailedRecipientException(thisPtr._connection.Reader!.StatusCode,
                                 thisPtr._toCollection[thisPtr._toIndex - 1].GetSmtpAddress(thisPtr._allowUnicode),
                                 response));
 
                         if (thisPtr._failedRecipientExceptions.Count == thisPtr._toCollection.Count)
                         {
-                            SmtpFailedRecipientException exception = null;
-                            if (thisPtr._toCollection.Count == 1)
-                            {
-                                exception = (SmtpFailedRecipientException)thisPtr._failedRecipientExceptions[0];
-                            }
-                            else
-                            {
-                                exception = new SmtpFailedRecipientsException(thisPtr._failedRecipientExceptions, true);
-                            }
+                            SmtpFailedRecipientException exception = thisPtr._toCollection.Count == 1 ?
+                                (SmtpFailedRecipientException)thisPtr._failedRecipientExceptions[0] :
+                                new SmtpFailedRecipientsException(thisPtr._failedRecipientExceptions, true);
                             exception.fatal = true;
                             thisPtr.InvokeCallback(exception);
                             return;
@@ -441,7 +425,7 @@ namespace System.Net.Mail
         {
             if (!result.CompletedSynchronously)
             {
-                SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState;
+                SendMailAsyncResult thisPtr = (SendMailAsyncResult)result.AsyncState!;
                 try
                 {
                     DataCommand.EndSend(result);
@@ -467,7 +451,7 @@ namespace System.Net.Mail
         }
 
         // Return the list of non-terminal failures (some recipients failed but not others).
-        internal SmtpFailedRecipientException GetFailedRecipientException()
+        internal SmtpFailedRecipientException? GetFailedRecipientException()
         {
             if (_failedRecipientExceptions.Count == 1)
             {
index 465668f..71bda79 100644 (file)
@@ -24,7 +24,7 @@ namespace System.Net.Mime
         private readonly EventHandler _onCloseHandler;
         private readonly bool _shouldEncodeLeadingDots;
         private readonly int _lineLength;
-        protected Stream _contentStream;
+        protected Stream _contentStream = null!; // set to null on dispose
         protected bool _isInContent;
 
         protected BaseWriter(Stream stream, bool shouldEncodeLeadingDots)
@@ -109,7 +109,7 @@ namespace System.Net.Mime
 
         internal Stream GetContentStream() => GetContentStream(null);
 
-        private Stream GetContentStream(MultiAsyncResult multiResult)
+        private Stream GetContentStream(MultiAsyncResult? multiResult)
         {
             if (_isInContent)
             {
@@ -128,7 +128,7 @@ namespace System.Net.Mime
             return cs;
         }
 
-        internal IAsyncResult BeginGetContentStream(AsyncCallback callback, object state)
+        internal IAsyncResult BeginGetContentStream(AsyncCallback? callback, object? state)
         {
             MultiAsyncResult multiResult = new MultiAsyncResult(this, callback, state);
 
@@ -146,7 +146,7 @@ namespace System.Net.Mime
 
         internal Stream EndGetContentStream(IAsyncResult result)
         {
-            object o = MultiAsyncResult.End(result);
+            object o = MultiAsyncResult.End(result)!;
             if (o is Exception e)
             {
                 ExceptionDispatchInfo.Throw(e);
@@ -158,7 +158,7 @@ namespace System.Net.Mime
 
         #region Cleanup
 
-        protected void Flush(MultiAsyncResult multiResult)
+        protected void Flush(MultiAsyncResult? multiResult)
         {
             if (_bufferBuilder.Length > 0)
             {
@@ -185,7 +185,7 @@ namespace System.Net.Mime
         {
             if (!result.CompletedSynchronously)
             {
-                MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState;
+                MultiAsyncResult multiResult = (MultiAsyncResult)result.AsyncState!;
                 BaseWriter thisPtr = (BaseWriter)multiResult.Context;
                 try
                 {
@@ -201,7 +201,7 @@ namespace System.Net.Mime
 
         internal abstract void Close();
 
-        protected abstract void OnClose(object sender, EventArgs args);
+        protected abstract void OnClose(object? sender, EventArgs args);
 
         #endregion Cleanup
 
index 0269710..be078ae 100644 (file)
@@ -18,14 +18,14 @@ namespace System.Net.Mime
         private const string FileNameKey = "filename";
         private const string SizeKey = "size";
 
-        private TrackingValidationObjectDictionary _parameters;
+        private TrackingValidationObjectDictionary? _parameters;
         private string _disposition;
-        private string _dispositionType;
+        private string _dispositionType = null!; // set by ctor or by helper called from ctor
         private bool _isChanged;
         private bool _isPersisted;
 
         private static readonly TrackingValidationObjectDictionary.ValidateAndParseValue s_dateParser =
-                new TrackingValidationObjectDictionary.ValidateAndParseValue(v => new SmtpDateTime(v.ToString()));
+                new TrackingValidationObjectDictionary.ValidateAndParseValue(v => new SmtpDateTime(v.ToString()!));
         // this will throw a FormatException if the value supplied is not a valid SmtpDateTime
 
         private static readonly TrackingValidationObjectDictionary.ValidateAndParseValue s_longParser =
@@ -67,7 +67,7 @@ namespace System.Net.Mime
 
         internal DateTime GetDateParameter(string parameterName)
         {
-            SmtpDateTime dateValue = ((TrackingValidationObjectDictionary)Parameters).InternalGet(parameterName) as SmtpDateTime;
+            SmtpDateTime? dateValue = ((TrackingValidationObjectDictionary)Parameters).InternalGet(parameterName) as SmtpDateTime;
             return dateValue == null ? DateTime.MinValue : dateValue.Date;
         }
 
@@ -93,12 +93,12 @@ namespace System.Net.Mime
             }
         }
 
-        public StringDictionary Parameters => _parameters ?? (_parameters = new TrackingValidationObjectDictionary(s_validators));
+        public StringDictionary Parameters => _parameters ??= new TrackingValidationObjectDictionary(s_validators);
 
         /// <summary>
         /// Gets the value of the Filename parameter.
         /// </summary>
-        public string FileName
+        public string? FileName
         {
             get { return Parameters[FileNameKey]; }
             set
@@ -170,7 +170,7 @@ namespace System.Net.Mime
         {
             get
             {
-                object sizeValue = ((TrackingValidationObjectDictionary)Parameters).InternalGet(SizeKey);
+                object? sizeValue = ((TrackingValidationObjectDictionary)Parameters).InternalGet(SizeKey);
                 return sizeValue == null ? -1 : (long)sizeValue;
             }
             set
@@ -185,7 +185,7 @@ namespace System.Net.Mime
             // via the headers.
             _disposition = contentDisposition;
             ParseValue();
-            headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition), ToString());
+            headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition)!, ToString());
             _isPersisted = true;
         }
 
@@ -193,7 +193,7 @@ namespace System.Net.Mime
         {
             if (IsChanged || !_isPersisted || forcePersist)
             {
-                headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition), ToString());
+                headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition)!, ToString());
                 _isPersisted = true;
             }
         }
@@ -206,7 +206,7 @@ namespace System.Net.Mime
             {
                 _disposition = Encode(false); // Legacy wire-safe format
                 _isChanged = false;
-                _parameters.IsChanged = false;
+                _parameters!.IsChanged = false;
                 _isPersisted = false;
             }
             return _disposition;
@@ -218,13 +218,13 @@ namespace System.Net.Mime
             builder.Append(_dispositionType); // Must not have unicode, already validated
 
             // Validate and encode unicode where required
-            foreach (string key in Parameters.Keys)
+            foreach (string? key in Parameters.Keys) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/3214
             {
                 builder.Append("; ");
-                EncodeToBuffer(key, builder, allowUnicode);
+                EncodeToBuffer(key!, builder, allowUnicode);
 
                 builder.Append('=');
-                EncodeToBuffer(_parameters[key], builder, allowUnicode);
+                EncodeToBuffer(_parameters![key!]!, builder, allowUnicode);
             }
 
             return builder.ToString();
@@ -232,7 +232,7 @@ namespace System.Net.Mime
 
         private static void EncodeToBuffer(string value, StringBuilder builder, bool allowUnicode)
         {
-            Encoding encoding = MimeBasePart.DecodeEncoding(value);
+            Encoding? encoding = MimeBasePart.DecodeEncoding(value);
             if (encoding != null) // Manually encoded elsewhere, pass through
             {
                 builder.Append('"').Append(value).Append('"');
@@ -250,7 +250,7 @@ namespace System.Net.Mime
             }
         }
 
-        public override bool Equals(object rparam)
+        public override bool Equals(object? rparam)
         {
             return rparam == null ?
                 false :
@@ -298,8 +298,8 @@ namespace System.Net.Mime
                         break;
                     }
 
-                    string paramAttribute = MailBnfHelper.ReadParameterAttribute(_disposition, ref offset, null);
-                    string paramValue;
+                    string? paramAttribute = MailBnfHelper.ReadParameterAttribute(_disposition, ref offset, null);
+                    string? paramValue;
 
                     // verify the next character after the parameter is correct
                     if (_disposition[offset++] != '=')
index bbe7c30..d3a183f 100644 (file)
@@ -3,6 +3,7 @@
 // See the LICENSE file in the project root for more information.
 
 using System.Collections.Specialized;
+using System.Diagnostics.CodeAnalysis;
 using System.Net.Mail;
 using System.Text;
 
@@ -23,8 +24,8 @@ namespace System.Net.Mime
     {
         private readonly TrackingStringDictionary _parameters = new TrackingStringDictionary();
 
-        private string _mediaType;
-        private string _subType;
+        private string _mediaType = null!; // initialized by helper called from ctor
+        private string _subType = null!; // initialized by helper called from ctor
         private bool _isChanged;
         private string _type;
         private bool _isPersisted;
@@ -59,7 +60,7 @@ namespace System.Net.Mime
             ParseValue();
         }
 
-        public string Boundary
+        public string? Boundary
         {
             get { return Parameters["boundary"]; }
             set
@@ -75,7 +76,7 @@ namespace System.Net.Mime
             }
         }
 
-        public string CharSet
+        public string? CharSet
         {
             get { return Parameters["charset"]; }
             set
@@ -125,18 +126,18 @@ namespace System.Net.Mime
             }
         }
 
-
+        [AllowNull]
         public string Name
         {
             get
             {
-                string value = Parameters["name"];
-                Encoding nameEncoding = MimeBasePart.DecodeEncoding(value);
+                string? value = Parameters["name"];
+                Encoding? nameEncoding = MimeBasePart.DecodeEncoding(value);
                 if (nameEncoding != null)
                 {
                     value = MimeBasePart.DecodeHeaderValue(value);
                 }
-                return value;
+                return value!;
             }
             set
             {
@@ -151,14 +152,13 @@ namespace System.Net.Mime
             }
         }
 
-
         public StringDictionary Parameters => _parameters;
 
         internal void Set(string contentType, HeaderCollection headers)
         {
             _type = contentType;
             ParseValue();
-            headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType), ToString());
+            headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType)!, ToString());
             _isPersisted = true;
         }
 
@@ -166,7 +166,7 @@ namespace System.Net.Mime
         {
             if (IsChanged || !_isPersisted || forcePersist)
             {
-                headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType), ToString());
+                headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType)!, ToString());
                 _isPersisted = true;
             }
         }
@@ -194,12 +194,12 @@ namespace System.Net.Mime
             builder.Append(_subType);  // Must not have unicode, already validated
 
             // Validate and encode unicode where required
-            foreach (string key in Parameters.Keys)
+            foreach (string? key in Parameters.Keys) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/3214
             {
                 builder.Append("; ");
-                EncodeToBuffer(key, builder, allowUnicode);
+                EncodeToBuffer(key!, builder, allowUnicode);
                 builder.Append('=');
-                EncodeToBuffer(_parameters[key], builder, allowUnicode);
+                EncodeToBuffer(_parameters[key!]!, builder, allowUnicode);
             }
 
             return builder.ToString();
@@ -207,7 +207,7 @@ namespace System.Net.Mime
 
         private static void EncodeToBuffer(string value, StringBuilder builder, bool allowUnicode)
         {
-            Encoding encoding = MimeBasePart.DecodeEncoding(value);
+            Encoding? encoding = MimeBasePart.DecodeEncoding(value);
             if (encoding != null) // Manually encoded elsewhere, pass through
             {
                 builder.Append('\"').Append(value).Append('"');
@@ -225,7 +225,7 @@ namespace System.Net.Mime
             }
         }
 
-        public override bool Equals(object rparam) =>
+        public override bool Equals(object? rparam) =>
             rparam == null ? false : string.Equals(ToString(), rparam.ToString(), StringComparison.OrdinalIgnoreCase);
 
         public override int GetHashCode() => ToString().ToLowerInvariant().GetHashCode();
@@ -235,7 +235,7 @@ namespace System.Net.Mime
         private void ParseValue()
         {
             int offset = 0;
-            Exception exception = null;
+            Exception? exception = null;
 
             try
             {
@@ -269,7 +269,7 @@ namespace System.Net.Mime
                             break;
                         }
 
-                        string paramAttribute = MailBnfHelper.ReadParameterAttribute(_type, ref offset, null);
+                        string? paramAttribute = MailBnfHelper.ReadParameterAttribute(_type, ref offset, null);
 
                         if (paramAttribute == null || paramAttribute.Length == 0)
                         {
@@ -277,7 +277,7 @@ namespace System.Net.Mime
                             break;
                         }
 
-                        string paramValue;
+                        string? paramValue;
                         if (offset >= _type.Length || _type[offset++] != '=')
                         {
                             exception = new FormatException(SR.ContentTypeInvalid);
index 6294e9d..ec74c63 100644 (file)
@@ -23,7 +23,7 @@ namespace System.Net.Mime
     /// </summary>
     internal class EightBitStream : DelegatedStream, IEncodableStream
     {
-        private WriteStateInfoBase _writeState;
+        private WriteStateInfoBase? _writeState;
 
         // Should we do RFC 2821 Section 4.5.2 encoding of leading dots on a line?
         // We make this optional because this stream may be used recursively and
@@ -51,7 +51,7 @@ namespace System.Net.Mime
         /// <param name="count">Count of bytes to write</param>
         /// <param name="callback">Callback to call when write completes</param>
         /// <param name="state">State to pass to callback</param>
-        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
         {
             if (buffer == null)
             {
index c2ec43e..6c4b282 100644 (file)
@@ -14,7 +14,7 @@ namespace System.Net.Mime
     /// </summary>
     internal class HeaderCollection : NameValueCollection
     {
-        private readonly MimeBasePart _part = null;
+        private readonly MimeBasePart? _part = null;
 
         // default constructor
         // intentionally override the default comparer in the derived base class
@@ -22,7 +22,9 @@ namespace System.Net.Mime
         {
         }
 
+#pragma warning disable CS8610 // Nullability of reference types in type of parameter doesn't match overridden member.
         public override void Remove(string name)
+#pragma warning restore CS8610
         {
             if (name == null)
             {
@@ -38,7 +40,7 @@ namespace System.Net.Mime
 
             if (id == MailHeaderID.ContentType && _part != null)
             {
-                _part.ContentType = null;
+                _part.ContentType = null!; // this throws ArgumentNullException
             }
             else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
             {
@@ -49,7 +51,9 @@ namespace System.Net.Mime
         }
 
 
-        public override string Get(string name)
+#pragma warning disable CS8610 // Nullability of reference types in type of parameter doesn't match overridden member.
+        public override string? Get(string name)
+#pragma warning restore CS8610
         {
             if (name == null)
             {
@@ -69,12 +73,14 @@ namespace System.Net.Mime
             }
             else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
             {
-                ((MimePart)_part).ContentDisposition.PersistIfNeeded(this, false);
+                ((MimePart)_part!).ContentDisposition!.PersistIfNeeded(this, false);
             }
             return base.Get(name);
         }
 
-        public override string[] GetValues(string name)
+#pragma warning disable CS8610 // Nullability of reference types in type of parameter doesn't match overridden member.
+        public override string[]? GetValues(string name)
+#pragma warning restore CS8610
         {
             if (name == null)
             {
@@ -94,7 +100,7 @@ namespace System.Net.Mime
             }
             else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
             {
-                ((MimePart)_part).ContentDisposition.PersistIfNeeded(this, false);
+                ((MimePart)_part).ContentDisposition!.PersistIfNeeded(this, false);
             }
             return base.GetValues(name);
         }
@@ -118,7 +124,9 @@ namespace System.Net.Mime
             }
         }
 
+#pragma warning disable CS8610 // Nullability of reference types in type of parameter doesn't match overridden member.
         public override void Set(string name, string value)
+#pragma warning restore CS8610
         {
             if (name == null)
             {
@@ -158,7 +166,7 @@ namespace System.Net.Mime
             }
             else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
             {
-                ((MimePart)_part).ContentDisposition.Set(value.ToLowerInvariant(), this);
+                ((MimePart)_part).ContentDisposition!.Set(value.ToLowerInvariant(), this);
             }
             else
             {
@@ -167,7 +175,9 @@ namespace System.Net.Mime
         }
 
 
+#pragma warning disable CS8610 // Nullability of reference types in type of parameter doesn't match overridden member.
         public override void Add(string name, string value)
+#pragma warning restore CS8610
         {
             if (name == null)
             {
@@ -201,7 +211,7 @@ namespace System.Net.Mime
             }
             else if (id == MailHeaderID.ContentDisposition && _part is MimePart)
             {
-                ((MimePart)_part).ContentDisposition.Set(value.ToLowerInvariant(), this);
+                ((MimePart)_part).ContentDisposition!.Set(value.ToLowerInvariant(), this);
             }
             else
             {
index 2b46a8d..c248ad1 100644 (file)
@@ -13,13 +13,13 @@ namespace System.Net.Mime
         internal const string DefaultCharSet = "utf-8";
         private static readonly char[] s_decodeEncodingSplitChars = new char[] { '?', '\r', '\n' };
 
-        protected ContentType _contentType;
-        protected ContentDisposition _contentDisposition;
-        private HeaderCollection _headers;
+        protected ContentType? _contentType;
+        protected ContentDisposition? _contentDisposition;
+        private HeaderCollection? _headers;
 
         internal MimeBasePart() { }
 
-        internal static bool ShouldUseBase64Encoding(Encoding encoding) =>
+        internal static bool ShouldUseBase64Encoding(Encoding? encoding) =>
             encoding == Encoding.Unicode || encoding == Encoding.UTF8 || encoding == Encoding.UTF32 || encoding == Encoding.BigEndianUnicode;
 
         //use when the length of the header is not known or if there is no header
@@ -27,7 +27,7 @@ namespace System.Net.Mime
             EncodeHeaderValue(value, encoding, base64Encoding, 0);
 
         //used when the length of the header name itself is known (i.e. Subject : )
-        internal static string EncodeHeaderValue(string value, Encoding encoding, bool base64Encoding, int headerLength)
+        internal static string EncodeHeaderValue(string value, Encoding? encoding, bool base64Encoding, int headerLength)
         {
             //no need to encode if it's pure ascii
             if (IsAscii(value, false))
@@ -35,10 +35,7 @@ namespace System.Net.Mime
                 return value;
             }
 
-            if (encoding == null)
-            {
-                encoding = Encoding.GetEncoding(DefaultCharSet);
-            }
+            encoding ??= Encoding.GetEncoding(DefaultCharSet);
 
             EncodedStreamFactory factory = new EncodedStreamFactory();
             IEncodableStream stream = factory.GetEncoderForHeader(encoding, base64Encoding, headerLength);
@@ -51,7 +48,7 @@ namespace System.Net.Mime
         private static readonly char[] s_headerValueSplitChars = new char[] { '\r', '\n', ' ' };
         private static readonly char[] s_questionMarkSplitChars = new char[] { '?' };
 
-        internal static string DecodeHeaderValue(string value)
+        internal static string DecodeHeaderValue(string? value)
         {
             if (string.IsNullOrEmpty(value))
             {
@@ -97,7 +94,7 @@ namespace System.Net.Mime
         // "=?utf-8?B?RmlsZU5hbWVf55CG0Y3Qq9C60I5jw4TRicKq0YIM0Y1hSsSeTNCy0Klh?="; // 3.5
         // With the addition of folding in 4.0, there may be multiple lines with encoding, only detect the first:
         // "=?utf-8?B?RmlsZU5hbWVf55CG0Y3Qq9C60I5jw4TRicKq0YIM0Y1hSsSeTNCy0Klh?=\r\n =?utf-8?B??=";
-        internal static Encoding DecodeEncoding(string value)
+        internal static Encoding? DecodeEncoding(string? value)
         {
             if (string.IsNullOrEmpty(value))
             {
@@ -135,9 +132,9 @@ namespace System.Net.Mime
             return true;
         }
 
-        internal string ContentID
+        internal string? ContentID
         {
-            get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentID)]; }
+            get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentID)!]; }
             set
             {
                 if (string.IsNullOrEmpty(value))
@@ -151,9 +148,9 @@ namespace System.Net.Mime
             }
         }
 
-        internal string ContentLocation
+        internal string? ContentLocation
         {
-            get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentLocation)]; }
+            get { return Headers[MailHeaderInfo.GetString(MailHeaderID.ContentLocation)!]; }
             set
             {
                 if (string.IsNullOrEmpty(value))
@@ -194,7 +191,7 @@ namespace System.Net.Mime
 
         internal ContentType ContentType
         {
-            get { return _contentType ?? (_contentType = new ContentType()); }
+            get { return _contentType ??= new ContentType(); }
             set
             {
                 if (value == null)
@@ -209,13 +206,13 @@ namespace System.Net.Mime
 
         internal void PrepareHeaders(bool allowUnicode)
         {
-            _contentType.PersistIfNeeded((HeaderCollection)Headers, false);
-            _headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType), _contentType.Encode(allowUnicode));
+            _contentType!.PersistIfNeeded((HeaderCollection)Headers, false);
+            _headers!.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentType)!, _contentType.Encode(allowUnicode));
 
             if (_contentDisposition != null)
             {
                 _contentDisposition.PersistIfNeeded((HeaderCollection)Headers, false);
-                _headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition), _contentDisposition.Encode(allowUnicode));
+                _headers.InternalSet(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition)!, _contentDisposition.Encode(allowUnicode));
             }
         }
 
@@ -224,8 +221,8 @@ namespace System.Net.Mime
             throw new NotImplementedException();
         }
 
-        internal virtual IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback,
-            bool allowUnicode, object state)
+        internal virtual IAsyncResult BeginSend(BaseWriter writer, AsyncCallback? callback,
+            bool allowUnicode, object? state)
         {
             throw new NotImplementedException();
         }
@@ -237,7 +234,7 @@ namespace System.Net.Mime
                 throw new ArgumentNullException(nameof(asyncResult));
             }
 
-            LazyAsyncResult castedAsyncResult = asyncResult as MimePartAsyncResult;
+            LazyAsyncResult? castedAsyncResult = asyncResult as MimePartAsyncResult;
 
             if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
             {
@@ -259,7 +256,7 @@ namespace System.Net.Mime
 
         internal class MimePartAsyncResult : LazyAsyncResult
         {
-            internal MimePartAsyncResult(MimeBasePart part, object state, AsyncCallback callback) : base(part, state, callback)
+            internal MimePartAsyncResult(MimeBasePart part, object? state, AsyncCallback? callback) : base(part, state, callback)
             {
             }
         }
index 96ae395..04b5ccf 100644 (file)
@@ -13,9 +13,9 @@ namespace System.Net.Mime
 {
     internal class MimeMultiPart : MimeBasePart
     {
-        private Collection<MimeBasePart> _parts;
+        private Collection<MimeBasePart>? _parts;
         private static int s_boundary;
-        private AsyncCallback _mimePartSentCallback;
+        private AsyncCallback? _mimePartSentCallback;
         private bool _allowUnicode;
 
         internal MimeMultiPart(MimeMultiPartType type)
@@ -53,22 +53,22 @@ namespace System.Net.Mime
             }
         }
 
-        internal void Complete(IAsyncResult result, Exception e)
+        internal void Complete(IAsyncResult result, Exception? e)
         {
             //if we already completed and we got called again,
             //it mean's that there was an exception in the callback and we
             //should just rethrow it.
 
-            MimePartContext context = (MimePartContext)result.AsyncState;
+            MimePartContext context = (MimePartContext)result.AsyncState!;
 
             if (context._completed)
             {
-                ExceptionDispatchInfo.Throw(e);
+                ExceptionDispatchInfo.Throw(e!);
             }
 
             try
             {
-                context._outputStream.Close();
+                context._outputStream!.Close();
             }
             catch (Exception ex)
             {
@@ -88,7 +88,7 @@ namespace System.Net.Mime
                 return;
             }
 
-            ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+            ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
 
             try
             {
@@ -102,7 +102,7 @@ namespace System.Net.Mime
 
         private void MimeWriterCloseCallbackHandler(IAsyncResult result)
         {
-            MimePartContext context = (MimePartContext)result.AsyncState;
+            MimePartContext context = (MimePartContext)result.AsyncState!;
             ((MimeWriter)context._writer).EndClose(result);
             Complete(result, null);
         }
@@ -114,7 +114,7 @@ namespace System.Net.Mime
                 return;
             }
 
-            ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+            ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
 
             try
             {
@@ -128,14 +128,14 @@ namespace System.Net.Mime
 
         private void MimePartSentCallbackHandler(IAsyncResult result)
         {
-            MimePartContext context = (MimePartContext)result.AsyncState;
+            MimePartContext context = (MimePartContext)result.AsyncState!;
             MimeBasePart part = (MimeBasePart)context._partsEnumerator.Current;
             part.EndSend(result);
 
             if (context._partsEnumerator.MoveNext())
             {
                 part = (MimeBasePart)context._partsEnumerator.Current;
-                IAsyncResult sendResult = part.BeginSend(context._writer, _mimePartSentCallback, _allowUnicode, context);
+                IAsyncResult sendResult = part.BeginSend(context._writer, _mimePartSentCallback!, _allowUnicode, context);
                 if (sendResult.CompletedSynchronously)
                 {
                     MimePartSentCallbackHandler(sendResult);
@@ -159,7 +159,7 @@ namespace System.Net.Mime
                 return;
             }
 
-            ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+            ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
 
             try
             {
@@ -173,9 +173,9 @@ namespace System.Net.Mime
 
         private void ContentStreamCallbackHandler(IAsyncResult result)
         {
-            MimePartContext context = (MimePartContext)result.AsyncState;
+            MimePartContext context = (MimePartContext)result.AsyncState!;
             context._outputStream = context._writer.EndGetContentStream(result);
-            context._writer = new MimeWriter(context._outputStream, ContentType.Boundary);
+            context._writer = new MimeWriter(context._outputStream!, ContentType.Boundary!);
             if (context._partsEnumerator.MoveNext())
             {
                 MimeBasePart part = (MimeBasePart)context._partsEnumerator.Current;
@@ -198,8 +198,8 @@ namespace System.Net.Mime
             }
         }
 
-        internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback, bool allowUnicode,
-            object state)
+        internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback? callback, bool allowUnicode,
+            object? state)
         {
             _allowUnicode = allowUnicode;
             PrepareHeaders(allowUnicode);
@@ -224,7 +224,7 @@ namespace System.Net.Mime
             }
 
             internal IEnumerator<MimeBasePart> _partsEnumerator;
-            internal Stream _outputStream;
+            internal Stream? _outputStream;
             internal LazyAsyncResult _result;
             internal BaseWriter _writer;
             internal bool _completed;
@@ -236,7 +236,7 @@ namespace System.Net.Mime
             PrepareHeaders(allowUnicode);
             writer.WriteHeaders(Headers, allowUnicode);
             Stream outputStream = writer.GetContentStream();
-            MimeWriter mimeWriter = new MimeWriter(outputStream, ContentType.Boundary);
+            MimeWriter mimeWriter = new MimeWriter(outputStream, ContentType.Boundary!);
 
             foreach (MimeBasePart part in Parts)
             {
index 26eab32..cd2c3dd 100644 (file)
@@ -17,26 +17,23 @@ namespace System.Net.Mime
     /// </summary>
     internal class MimePart : MimeBasePart, IDisposable
     {
-        private Stream _stream = null;
+        private Stream? _stream;
         private bool _streamSet = false;
         private bool _streamUsedOnce = false;
-        private AsyncCallback _readCallback;
-        private AsyncCallback _writeCallback;
+        private AsyncCallback? _readCallback;
+        private AsyncCallback? _writeCallback;
         private const int maxBufferSize = 0x4400;  //seems optimal for send based on perf analysis
 
         internal MimePart() { }
 
         public void Dispose()
         {
-            if (_stream != null)
-            {
-                _stream.Close();
-            }
+            _stream?.Close();
         }
 
-        internal Stream Stream => _stream;
+        internal Stream? Stream => _stream;
 
-        internal ContentDisposition ContentDisposition
+        internal ContentDisposition? ContentDisposition
         {
             get { return _contentDisposition; }
             set
@@ -44,11 +41,11 @@ namespace System.Net.Mime
                 _contentDisposition = value;
                 if (value == null)
                 {
-                    ((HeaderCollection)Headers).InternalRemove(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition));
+                    ((HeaderCollection)Headers).InternalRemove(MailHeaderInfo.GetString(MailHeaderID.ContentDisposition)!);
                 }
                 else
                 {
-                    _contentDisposition.PersistIfNeeded((HeaderCollection)Headers, true);
+                    _contentDisposition!.PersistIfNeeded((HeaderCollection)Headers, true);
                 }
             }
         }
@@ -57,7 +54,7 @@ namespace System.Net.Mime
         {
             get
             {
-                string value = Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)];
+                string value = Headers[MailHeaderInfo.GetString(MailHeaderID.ContentTransferEncoding)!]!;
                 if (value.Equals("base64", StringComparison.OrdinalIgnoreCase))
                 {
                     return TransferEncoding.Base64;
@@ -114,7 +111,7 @@ namespace System.Net.Mime
 
             if (_streamSet)
             {
-                _stream.Close();
+                _stream!.Close();
                 _stream = null;
                 _streamSet = false;
             }
@@ -125,7 +122,7 @@ namespace System.Net.Mime
             TransferEncoding = TransferEncoding.Base64;
         }
 
-        internal void SetContent(Stream stream, string name, string mimeType)
+        internal void SetContent(Stream stream, string? name, string? mimeType)
         {
             if (stream == null)
             {
@@ -143,7 +140,7 @@ namespace System.Net.Mime
             SetContent(stream);
         }
 
-        internal void SetContent(Stream stream, ContentType contentType)
+        internal void SetContent(Stream stream, ContentType? contentType)
         {
             if (stream == null)
             {
@@ -153,16 +150,16 @@ namespace System.Net.Mime
             SetContent(stream);
         }
 
-        internal void Complete(IAsyncResult result, Exception e)
+        internal void Complete(IAsyncResult result, Exception? e)
         {
             //if we already completed and we got called again,
             //it mean's that there was an exception in the callback and we
             //should just rethrow it.
 
-            MimePartContext context = (MimePartContext)result.AsyncState;
+            MimePartContext context = (MimePartContext)result.AsyncState!;
             if (context._completed)
             {
-                ExceptionDispatchInfo.Throw(e);
+                ExceptionDispatchInfo.Throw(e!);
             }
 
             try
@@ -191,7 +188,7 @@ namespace System.Net.Mime
                 return;
             }
 
-            ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+            ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
 
             try
             {
@@ -205,11 +202,11 @@ namespace System.Net.Mime
 
         internal void ReadCallbackHandler(IAsyncResult result)
         {
-            MimePartContext context = (MimePartContext)result.AsyncState;
-            context._bytesLeft = Stream.EndRead(result);
+            MimePartContext context = (MimePartContext)result.AsyncState!;
+            context._bytesLeft = Stream!.EndRead(result);
             if (context._bytesLeft > 0)
             {
-                IAsyncResult writeResult = context._outputStream.BeginWrite(context._buffer, 0, context._bytesLeft, _writeCallback, context);
+                IAsyncResult writeResult = context._outputStream!.BeginWrite(context._buffer, 0, context._bytesLeft, _writeCallback, context);
                 if (writeResult.CompletedSynchronously)
                 {
                     WriteCallbackHandler(writeResult);
@@ -228,7 +225,7 @@ namespace System.Net.Mime
                 return;
             }
 
-            ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+            ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
 
             try
             {
@@ -242,9 +239,9 @@ namespace System.Net.Mime
 
         internal void WriteCallbackHandler(IAsyncResult result)
         {
-            MimePartContext context = (MimePartContext)result.AsyncState;
-            context._outputStream.EndWrite(result);
-            IAsyncResult readResult = Stream.BeginRead(context._buffer, 0, context._buffer.Length, _readCallback, context);
+            MimePartContext context = (MimePartContext)result.AsyncState!;
+            context._outputStream!.EndWrite(result);
+            IAsyncResult readResult = Stream!.BeginRead(context._buffer, 0, context._buffer.Length, _readCallback, context);
             if (readResult.CompletedSynchronously)
             {
                 ReadCallbackHandler(readResult);
@@ -273,13 +270,13 @@ namespace System.Net.Mime
 
         internal void ContentStreamCallbackHandler(IAsyncResult result)
         {
-            MimePartContext context = (MimePartContext)result.AsyncState;
+            MimePartContext context = (MimePartContext)result.AsyncState!;
             Stream outputStream = context._writer.EndGetContentStream(result);
             context._outputStream = GetEncodedStream(outputStream);
 
             _readCallback = new AsyncCallback(ReadCallback);
             _writeCallback = new AsyncCallback(WriteCallback);
-            IAsyncResult readResult = Stream.BeginRead(context._buffer, 0, context._buffer.Length, _readCallback, context);
+            IAsyncResult readResult = Stream!.BeginRead(context._buffer, 0, context._buffer.Length, _readCallback, context);
             if (readResult.CompletedSynchronously)
             {
                 ReadCallbackHandler(readResult);
@@ -293,7 +290,7 @@ namespace System.Net.Mime
                 return;
             }
 
-            ((MimePartContext)result.AsyncState)._completedSynchronously = false;
+            ((MimePartContext)result.AsyncState!)._completedSynchronously = false;
 
             try
             {
@@ -314,7 +311,7 @@ namespace System.Net.Mime
                 _buffer = new byte[maxBufferSize];
             }
 
-            internal Stream _outputStream;
+            internal Stream? _outputStream;
             internal LazyAsyncResult _result;
             internal int _bytesLeft;
             internal BaseWriter _writer;
@@ -323,7 +320,7 @@ namespace System.Net.Mime
             internal bool _completedSynchronously = true;
         }
 
-        internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback callback, bool allowUnicode, object state)
+        internal override IAsyncResult BeginSend(BaseWriter writer, AsyncCallback? callback, bool allowUnicode, object? state)
         {
             PrepareHeaders(allowUnicode);
             writer.WriteHeaders(Headers, allowUnicode);
@@ -370,7 +367,7 @@ namespace System.Net.Mime
         {
             if (_streamUsedOnce)
             {
-                if (Stream.CanSeek)
+                if (Stream!.CanSeek)
                 {
                     Stream.Seek(0, SeekOrigin.Begin);
                     _streamUsedOnce = false;
index 85b878f..bf7c66c 100644 (file)
@@ -34,13 +34,13 @@ namespace System.Net.Mime
             if (headers == null)
                 throw new ArgumentNullException(nameof(headers));
 
-            foreach (string key in headers)
-                WriteHeader(key, headers[key], allowUnicode);
+            foreach (string? key in headers) // TODO-NULLABLE: https://github.com/dotnet/csharplang/issues/3214
+                WriteHeader(key!, headers[key]!, allowUnicode);
         }
 
         #region Cleanup
 
-        internal IAsyncResult BeginClose(AsyncCallback callback, object state)
+        internal IAsyncResult BeginClose(AsyncCallback? callback, object? state)
         {
             MultiAsyncResult multiResult = new MultiAsyncResult(this, callback, state);
 
@@ -65,7 +65,7 @@ namespace System.Net.Mime
             _stream.Close();
         }
 
-        private void Close(MultiAsyncResult multiResult)
+        private void Close(MultiAsyncResult? multiResult)
         {
             _bufferBuilder.Append(s_crlf);
             _bufferBuilder.Append(s_DASHDASH);
@@ -81,13 +81,13 @@ namespace System.Net.Mime
         /// </summary>
         /// <param name="sender">Sender of the close event</param>
         /// <param name="args">Event args (not used)</param>
-        protected override void OnClose(object sender, EventArgs args)
+        protected override void OnClose(object? sender, EventArgs args)
         {
             if (_contentStream != sender)
                 return; // may have called WriteHeader
 
             _contentStream.Flush();
-            _contentStream = null;
+            _contentStream = null!;
             _writeBoundary = true;
 
             _isInContent = false;
index 74553b5..a6a8b78 100644 (file)
@@ -11,7 +11,7 @@ namespace System.Net.Mime
         private readonly object _context;
         private int _outstanding;
 
-        internal MultiAsyncResult(object context, AsyncCallback callback, object state) : base(context, state, callback)
+        internal MultiAsyncResult(object context, AsyncCallback? callback, object? state) : base(context, state, callback)
         {
             _context = context;
         }
@@ -40,7 +40,7 @@ namespace System.Net.Mime
 
         internal void CompleteSequence() => Decrement();
 
-        internal static object End(IAsyncResult result)
+        internal static object? End(IAsyncResult result)
         {
             MultiAsyncResult thisPtr = (MultiAsyncResult)result;
             thisPtr.InternalWaitForCompletion();
index 560d094..b5cf458 100644 (file)
@@ -40,7 +40,7 @@ namespace System.Net.Mime
              255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, // F
         };
 
-        private ReadStateInfo _readState;
+        private ReadStateInfo? _readState;
         private readonly WriteStateInfoBase _writeState;
 
         internal QEncodedStream(WriteStateInfoBase wsi) : base(new MemoryStream())
@@ -52,7 +52,7 @@ namespace System.Net.Mime
 
         internal WriteStateInfoBase WriteState => _writeState;
 
-        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
         {
             if (buffer == null)
             {
@@ -326,7 +326,7 @@ namespace System.Net.Mime
 
             private int _written;
 
-            internal WriteAsyncResult(QEncodedStream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+            internal WriteAsyncResult(QEncodedStream parent, byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
                 : base(null, state, callback)
             {
                 _parent = parent;
@@ -352,7 +352,7 @@ namespace System.Net.Mime
             {
                 if (!result.CompletedSynchronously)
                 {
-                    WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState;
+                    WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState!;
                     try
                     {
                         thisPtr.CompleteWrite(result);
index d3e9b82..0e8d78f 100644 (file)
@@ -58,8 +58,8 @@ namespace System.Net.Mime
         private static ReadOnlySpan<byte> HexEncodeMap => new byte[] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70 };
 
         private readonly int _lineLength;
-        private ReadStateInfo _readState;
-        private WriteStateInfoBase _writeState;
+        private ReadStateInfo? _readState;
+        private WriteStateInfoBase? _writeState;
 
         /// <summary>
         /// ctor.
@@ -83,9 +83,9 @@ namespace System.Net.Mime
 
         private ReadStateInfo ReadState => _readState ?? (_readState = new ReadStateInfo());
 
-        internal WriteStateInfoBase WriteState => _writeState ?? (_writeState = new WriteStateInfoBase(1024, null, null, _lineLength));
+        internal WriteStateInfoBase WriteState => _writeState ??= new WriteStateInfoBase(1024, null, null, _lineLength);
 
-        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
+        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
         {
             if (buffer == null)
             {
@@ -230,7 +230,7 @@ namespace System.Net.Mime
                 //add two to the encoded Byte Length to be conservative so that we guarantee that the line length is acceptable
                 if ((_lineLength != -1 && WriteState.CurrentLineLength + SizeOfEncodedChar + 2 >= _lineLength && (buffer[cur] == ' ' ||
                     buffer[cur] == '\t' || buffer[cur] == '\r' || buffer[cur] == '\n')) ||
-                    _writeState.CurrentLineLength + SizeOfEncodedChar + 2 >= EncodedStreamFactory.DefaultMaxLineLength)
+                    _writeState!.CurrentLineLength + SizeOfEncodedChar + 2 >= EncodedStreamFactory.DefaultMaxLineLength)
                 {
                     if (WriteState.Buffer.Length - WriteState.Length < SizeOfSoftCRLF)
                     {
@@ -376,7 +376,7 @@ namespace System.Net.Mime
             private static readonly AsyncCallback s_onWrite = new AsyncCallback(OnWrite);
             private int _written;
 
-            internal WriteAsyncResult(QuotedPrintableStream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback)
+            internal WriteAsyncResult(QuotedPrintableStream parent, byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) : base(null, state, callback)
             {
                 _parent = parent;
                 _buffer = buffer;
@@ -401,7 +401,7 @@ namespace System.Net.Mime
             {
                 if (!result.CompletedSynchronously)
                 {
-                    WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState;
+                    WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState!;
                     try
                     {
                         thisPtr.CompleteWrite(result);
index 069ce43..c397efb 100644 (file)
@@ -6,8 +6,8 @@ namespace System.Net.Mime
 {
     internal class WriteStateInfoBase
     {
-        protected readonly byte[] _header;
-        protected readonly byte[] _footer;
+        protected readonly byte[]? _header;
+        protected readonly byte[]? _footer;
         protected readonly int _maxLineLength;
 
         protected byte[] _buffer;
@@ -28,12 +28,12 @@ namespace System.Net.Mime
             _currentBufferUsed = 0;
         }
 
-        internal WriteStateInfoBase(int bufferSize, byte[] header, byte[] footer, int maxLineLength)
+        internal WriteStateInfoBase(int bufferSize, byte[]? header, byte[]? footer, int maxLineLength)
             : this(bufferSize, header, footer, maxLineLength, 0)
         {
         }
 
-        internal WriteStateInfoBase(int bufferSize, byte[] header, byte[] footer, int maxLineLength, int mimeHeaderLength)
+        internal WriteStateInfoBase(int bufferSize, byte[]? header, byte[]? footer, int maxLineLength, int mimeHeaderLength)
         {
             _buffer = new byte[bufferSize];
             _header = header;
@@ -44,9 +44,9 @@ namespace System.Net.Mime
             _currentBufferUsed = 0;
         }
 
-        internal int FooterLength => _footer.Length;
-        internal byte[] Footer => _footer;
-        internal byte[] Header => _header;
+        internal int FooterLength => _footer!.Length;
+        internal byte[]? Footer => _footer;
+        internal byte[]? Header => _header;
         internal byte[] Buffer => _buffer;
         internal int Length => _currentBufferUsed;
         internal int CurrentLineLength => _currentLineLength;
index 7a32ad0..e4f86e7 100644 (file)
@@ -22,7 +22,7 @@ namespace System.Net
 
         internal bool IsChanged { get { return _isChanged; } set { _isChanged = value; } }
 
-        public override void Add(string key, string value)
+        public override void Add(string key, string? value)
         {
             if (_isReadOnly)
             {
@@ -55,7 +55,7 @@ namespace System.Net
             _isChanged = true;
         }
 
-        public override string this[string key]
+        public override string? this[string key]
         {
             get { return base[key]; }
             set
index 1c75a8c..777e5f2 100644 (file)
@@ -22,7 +22,7 @@ namespace System.Net
         // even though validators may exist, we should not initialize this initially since by default it is empty
         // and it may never be populated with values if the user does not set them
         private readonly Dictionary<string, ValidateAndParseValue> _validators;
-        private Dictionary<string, object> _internalObjects = null;
+        private Dictionary<string, object>? _internalObjects = null;
 
         #endregion
 
@@ -41,7 +41,7 @@ namespace System.Net
 
         // precondition:  key must not be null
         // addValue determines if we are doing a set (false) or an add (true)
-        private void PersistValue(string key, string value, bool addValue)
+        private void PersistValue(string key, string? value, bool addValue)
         {
             Debug.Assert(key != null, "key was null");
 
@@ -56,7 +56,7 @@ namespace System.Net
             // in addition, a key with an empty value is not valid so we do not persist those either
             if (!string.IsNullOrEmpty(value))
             {
-                ValidateAndParseValue foundEntry;
+                ValidateAndParseValue? foundEntry;
                 if (_validators != null && _validators.TryGetValue(key, out foundEntry))
                 {
                     // run the validator for this key; it will throw if the value is invalid
@@ -116,10 +116,10 @@ namespace System.Net
 
         // public interface only allows strings so this provides a means
         // to get the objects when they are not strings
-        internal object InternalGet(string key)
+        internal object? InternalGet(string key)
         {
             // internalObjects will throw if the key is not found so we must check it
-            object foundObject;
+            object? foundObject;
             if (_internalObjects != null && _internalObjects.TryGetValue(key, out foundObject))
             {
                 return foundObject;
@@ -152,7 +152,7 @@ namespace System.Net
 
         #region Public Fields
 
-        public override string this[string key]
+        public override string? this[string key]
         {
             get
             {
@@ -170,7 +170,7 @@ namespace System.Net
 
         #region Public Methods
 
-        public override void Add(string key, string value)
+        public override void Add(string key, string? value)
         {
             PersistValue(key, value, true);
         }
index 1312f99..6750ab3 100644 (file)
@@ -3,6 +3,7 @@
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
     <StringResourcesPath>../../src/Resources/Strings.resx</StringResourcesPath>
     <TargetFrameworks>$(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix</TargetFrameworks>
+    <Nullable>annotations</Nullable>
   </PropertyGroup>
   <ItemGroup>
     <Compile Include="Base64EncodingTest.cs" />
index 4b1a3eb..af93167 100644 (file)
@@ -65,7 +65,7 @@ namespace System.Net
             }
         }
 
-        internal string Spn
+        internal string? Spn
         {
             get
             {
index cbd1ca5..15773ce 100644 (file)
@@ -16,7 +16,7 @@ namespace System.Net.Security
     {
         internal static IIdentity GetIdentity(NTAuthentication context)
         {
-            string name = context.Spn;
+            string name = context.Spn!;
             string protocol = context.ProtocolName;
 
             if (context.IsServer)
index 9c80ef9..a03fe69 100644 (file)
@@ -21,7 +21,7 @@ namespace System.Net.Security
         internal static IIdentity GetIdentity(NTAuthentication context)
         {
             IIdentity? result = null;
-            string name = context.IsServer ? context.AssociatedName! : context.Spn;
+            string name = context.IsServer ? context.AssociatedName! : context.Spn!;
             string protocol = context.ProtocolName;
 
             if (context.IsServer)