Resolving Build Errors When Targeting Mulitple Framework Versions

Here’s a tip that I hope can help some other folks when working on a solution that targets multiple versions of the .Net Framework.

As a developer, I tend to have a short memory and flush it often. When I start using framework features, I let myself easily move on, mentally, from the time when said features didn’t exist. 2010 is sooo last year. Or four years ago, but who’s keeping count.

This morning, I started getting the following error while working on Glimpse, where the primary project is authored in .Net 4.5:

System.Enum does not contain a definition for ‘TryParse’.

image

A quick check on MSDN shows that System.Enum.aspx) does indeed contain a definition for TryParse, but only in 4.0 and higher.

 image

If you peek back at the Error List screen cap, you’ll see the hint to what was going on in the “Project” column. Namely, one of the projects in the Glimpse solution used for backwards compatibility targets an older version of the .Net Framework.

So, this is actually pretty easy to resolve, and I have two obvious choices:

  1. I can test to see if the NET35 compilation symbol is defined and write two copies of the code, one with, one without the use of TryParse, or,
  2. Just use the cross-framework supported approach from way back in the day (2010), where we would wrap up the Enum.Parse call in a try-catch block.

For brevity of code, I chose #2.

    try
{
order = (ScriptOrder)Enum.Parse(typeof(ScriptOrder), orderName);
}
catch (ArgumentException)
{
return new StatusCodeResourceResult(404, string.Format(“Could not resolve ScriptOrder for value provided ‘{0}’.”, orderName));
}

Should Glimpse drop support for .Net 3.5 down the road, this would be an easy pull request to update and make use of the new(ish) TryParse method.

Filed under the category of “things to keep fresh in your mind when working on open source”.

For more on multi-targeted solutions, you can check out this read on MSDN.aspx).