4
\$\begingroup\$

I have tried the following code:

SystemUser user = (SystemUser)Session["CurrentUser"];
Data.Configuration configuration = db.Configurations.Single(c => c.ID == user.ID);
MailAddress from = new MailAddress("noreply@test.com", "Test");
if (configuration.EmailFromAddress != null)
{
    from = new MailAddress(configuration.EmailFromAddress, "Test"); 
}

Here I declare the from variable of the MailAddress class with a default value, and if configuration.EmailFromAddress exists, I am assigning that value to the from.

Is this following best practice?

Here, the MailAddress class is calling twice to assign the value. Is it good performance and memory wise? Another implementation is using a string variable:

SystemUser user = (SystemUser)Session["CurrentUser"];
Data.Configuration configuration = db.Configurations.Single(c => c.ID == user.ID);
string fromAddress = "noreply@test.com";
if (configuration.EmailFromAddress != null)
{
    fromAddress = configuration.EmailFromAddress;
}
MailAddress from = new MailAddress(fromAddress, "Test");

Which one follows best practice?

\$\endgroup\$
  • 1
    \$\begingroup\$ "Is it good performance and memory wise?" It's very likely the difference won't be significant. Don't micro-optimize prematurely. \$\endgroup\$ – svick Oct 10 '14 at 13:54
6
\$\begingroup\$

If you are sure that configuration.EmailFromAddress will always be valid or null, I'd suggest using the null-coalescing operator (??)

SystemUser user = (SystemUser)Session["CurrentUser"];
Data.Configuration configuration = db.Configurations.Single(c => c.ID == user.ID);
var fromAddress = configuration.EmailFromAddress ?? "noreply@test.com";
MailAddress from = new MailAddress(fromAddress, "Test");

In the case that configuration.EmailFromAddress can also be empty, I'd use the ternary operator

SystemUser user = (SystemUser)Session["CurrentUser"];
Data.Configuration configuration = db.Configurations.Single(c => c.ID == user.ID);
var fromAddress = String.IsNullOrEmpty(configuration.EmailFromAddress) ? configuration.EmailFromAddress : "noreply@test.com";
MailAddress from = new MailAddress(fromAddress, "Test");
\$\endgroup\$
2
\$\begingroup\$

Assuming that EmailFromAddress is just a plain field or property then the second version is better because you are not creating an unnecessary object. However when you are comparing strings it is often better to use string.IsNullOrEmpty() or string.IsNullOrWhitespace() (available since .NET 4.0) depending of what the possible values might be. Saul's answer already contains the code showing how to do this.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.