Reputation: 614
both SmtpClient and MailMessage implements IDisposable so i thought of making my code like this
using (SmtpClient smtpClient = new SmtpClient("xxx", 587))
{
smtpClient.Credentials = new System.Net.NetworkCredential("email", "pass");
smtpClient.EnableSsl = true;
using (MailMessage mail = new MailMessage())
{
mail.Subject = "subject";
mail.From = new MailAddress("email", "name");
mail.To.Add(new MailAddress("email"));
mail.Body = "body";
mail.IsBodyHtml = true;
smtpClient.Send(mail);
}
}
am i doing it right using 2 using statements or only the first using statement is necessary?
thanks
Upvotes: 1
Views: 826
Reputation: 3574
When nesting using
statements, it’s more idiomatic to do it without indentation:
using (SmtpClient smtpClient = new SmtpClient("xxx", 587))
using (MailMessage mail = new MailMessage())
{
smtpClient.Credentials = new System.Net.NetworkCredential("email", "pass");
smtpClient.EnableSsl = true;
mail.Subject = "subject";
mail.From = new MailAddress("email", "name");
mail.To.Add(new MailAddress("email"));
mail.Body = "body";
mail.IsBodyHtml = true;
smtpClient.Send(mail);
}
This isn’t always possible, because you sometimes need to do some processing between the first and the second using
. It works in your example, though.
Upvotes: 1
Reputation: 634
There is nothing inherently wrong with having multiple using statements. It keeps the lifetime of objects to the minimum which is not a bad thing to do.
Upvotes: 1