patterncsharpModerate
Cleaning up conditional statements regarding new values
Viewed 0 times
newstatementsregardingconditionalvaluescleaning
Problem
Please suggest ways of cleaning up this code.
Hashtable newValues = e.Values;
string NewPosition = null;
string NewFirst = null;
string NewLast = null;
string NewEmail = null;
int NewAppt = 0;
if (newValues["Position"] == null)
{
NewPosition = "";
}
else
{
NewPosition = newValues["Position"].ToString();
}
if (newValues["First Name"] == null)
{
NewFirst = "";
}
else
{
NewFirst = newValues["First Name"].ToString();
}
if (newValues["Last Name"] == null)
{
NewLast = "";
}
else
{
NewLast = newValues["Last Name"].ToString();
}
if (newValues["Email"] == null)
{
NewEmail = "";
}
else
{
NewEmail = newValues["Email"].ToString();
}
if (newValues["Appts"] == null)
{
NewAppt = 0;
}
else
{
NewAppt = 1;
}Solution
You can use the null-coalescing operator
The core of this approach is this expression:
The
For the last one, use
?? like this:NewPosition = (newValues["Position"] ?? "").ToString();The core of this approach is this expression:
newValues["Position"] ?? ""The
?? operator evaluates the left expression first (i.e. newValues["Position"]), and uses it as the result if it's not null. If the first expression is null, the second expression is evaluated, and its result is returned as the overall result of the expression.For the last one, use
?:NewAppt = (newValues["Appts"] != null) ? 1 : 0;Code Snippets
NewPosition = (newValues["Position"] ?? "").ToString();newValues["Position"] ?? ""NewAppt = (newValues["Appts"] != null) ? 1 : 0;Context
StackExchange Code Review Q#15928, answer score: 15
Revisions (0)
No revisions yet.