var smtp = new SmtpClient
{
Host =smtpHost,
Port = smtpPort,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, mailFromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
}
)
{
smtp.Send(message);
}
The last parenthesis (4 lines from bottom) closes the using statement. I must be missing something obvious here but the code compiles, passes resharper and yet the var message is used outside the using statement. In fact if I put it inside the using statement it fails to build.
In fact from this https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement
"The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object): "
message should already have been out of scope and possibly disposed.