RSS

How to avoid If statements by using inline comparison with c#

29 Feb

So Another thing I see alot of especialy from jr devs is a if statment that changes the way you load a object based on on of the items being refrenced to load that object with data take the following example

DeliveryCompanyInfo.Columns.AddRange(new DataColumn[]
{
	new DataColumn("CompanyName"),
	new DataColumn("Name"),
	new DataColumn("Phone"),
	new DataColumn("Address1"),
	new DataColumn("Address2"),
	new DataColumn("City"),
	new DataColumn("State"),
	new DataColumn("Zip")
});
if (string.IsNullOrEmpty(txtToAddress2.Text))
{
       DeliveryCompanyInfo.Rows.Add(DeliveryCompany.Text, txtToName.Text, txtToPhone.Text, txtToAddress1, " ", txtToCity.Text, ddlToState.SelectedValue, txtToZip.Text);
}
else
{
DeliveryCompanyInfo.Rows.Add(DeliveryCompany.Text, txtToName.Text, txtToPhone.Text, txtToAddress1, txtToAddress2.Text, txtToCity.Text, ddlToState.SelectedValue, txtToZip.Text);
}</pre>

This is bad because it puts in a unneeded switch and adds complexity to maintenance instead do this

DeliveryCompanyInfo.Rows.Add( DeliveryCompany.Text, txtToName.Text, txtToPhone.Text, txtToAddress1, (string.IsNullOrWhiteSpace(txtToAddress2.Text)) ? " " : txtToAddress2.Text , txtToCity.Text, ddlToState.SelectedValue, txtToZip.Text);

this does the change inline by doing a comparison that returns a bool and then inserting the proper value based on the result the basic function is like this

(Boolean) ? (TrueValue):(FalseValue)

pretty simple huh? so if you can use this and avoid if statements also you can use multiple comparisons using the || or && in the Boolean block.

Advertisements
 
Leave a comment

Posted by on February 29, 2012 in C#

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: