Extension Method to Convert Types

I was working on a project where I needed to compare values from two different systems. I needed a way to convert the data based on the type, which was known, from a string value that was pulled from XML or typed in by the user as an override value. Using LINQ to compare the values was problematic, as a decimal value could be input as “0” or “0.0” or “0.00” etc. Dates are an obvious issue. So I used an extension method to convert types.

Let’s take a look at the following code:


private void ConvertDecimals1()
{
	try
	{
		string[] valsFromXML = new string[] {"0", "1", "2" };
		string testVal = "0.00";

		var myVals = from objVal in valsFromXML
					 where objVal == testVal
					 select objVal;

		Console.WriteLine(myVals.Count().ToString());

	}
	catch (Exception)
	{ throw; }
}

Running this code produces a count of zero, which you would expect for a comparison of this nature. But wait, System.String implements IComparable, so maybe we could use it to quickly resolve our issue:

var myVals = from objVal in valsFromXML
			 where (objVal.CompareTo(testVal) == 0)
			 select objVal;

But alas, no easy solution here, this also does not produce a match, unless the strings were formatted identically. There is no getting around converting the values. Fortunately, we have some conversion functions that we could use to accomplish this task:

var myVals = from objVal in valsFromXML
			 where Convert.ToDecimal(objVal) == Convert.ToDecimal(testVal)
			 select objVal;

Ah, perfect this produces the count of one that we were looking for. This code will work great, so long as it never has a code review or goes into production. Since the source values are strings, you don’t have any control over what is being passed in. In this case, the best bet is to use the TryParse method on the type to convert the values:

decimal decValue;
decimal.TryParse(testVal, out decValue);

Which would work great, except we still have the collection of values being passed in that would have to be handled in a foreach loop to accomplish this goal.

Extension methods to the rescue again. Let’s create a new static class and encapsulate the logic we need to convert the string to the decimal values:

public static class ExtMethods
{
	public static decimal? ToDecimal(this string value)
	{
		Decimal decItem;
		if (Decimal.TryParse(value, out decItem))
		{ return decItem; }
		else
		{ return null; }
	}
}

This effectively adds the ability to attempt to convert the string value to a decimal and return the value. Notice that I didn’t just return the decItem variable contents. This is because if the TryParse fails, it will fill the value with a decimal value of zero, which will pass a comparison to zero. This is not acceptable, so we still need to check that the conversion occurred successfully before we return the value. Returning null will not cause LINQ to raise an exception.

So now we can modify our LINQ query as follows:

var myVals = from objVal in valsFromXML
			 where objVal.ToDecimal() == testVal.ToDecimal()
			 select objVal;

This will give us a safe, encapsulated, reusable way to compare values that need to be converted from strings.