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.

Author: Jack Yasgar

Jack Yasgar has been developing software for various industries for two decades. Currently, he utilizes C#, JQuery, JavaScript, SQL Server with stored procedures and/or Entity Framework to produce MVC responsive web sites that converse to a service layer utilizing RESTful API in Web API 2.0 or Microsoft WCF web services. The infrastructure can be internal, shared or reside in Azure. Jack has designed dozens of relational databases that use the proper primary keys and foreign keys to allow for data integrity moving forward. While working in a Scrum/Agile environment, he is a firm believer that quality software comes from quality planning. Without getting caught up in analysis paralysis, it is still possible to achieve a level of design that allows an agile team to move forward quickly while keeping re-work to a minimum. Jack believes, “The key to long term software success is adhering to the SOLID design principles. Software written quickly, using wizards and other methods can impress the business sponsor / product owner for a short period of time. Once the honeymoon is over, the product owner will stay enamored when the team can implement changes quickly and fix bugs in minutes, not hours or days.” Jack has become certified by the Object Management Group as OCUP II (OMG Certified UML Professional) in addition to his certification as a Microsoft Certified Professional. The use of the Unified Modeling Language (UML) provides a visual guide to Use Cases and Activities that can guide the product owner in designing software that meets the end user needs. The software development teams then use the same drawings to create their Unit Tests to make sure that the software meets all those needs. The QA testing team can use the UML drawings as a guide to produce test cases. Once the software is in production, the UML drawings become a reference for business users and support staff to know what decisions are happening behind the scenes to guide their support efforts.

Leave a Reply

Your email address will not be published. Required fields are marked *