Detect target framework version at compile time

Viewed 32713

I have some code which makes use of Extension Methods, but compiles under .NET 2.0 using the compiler in VS2008. To facilitate this, I had to declare ExtensionAttribute:

/// <summary>
/// ExtensionAttribute is required to define extension methods under .NET 2.0
/// </summary>
public sealed class ExtensionAttribute : Attribute
{
}

However, I'd now like the library in which that class is contained to also be compilable under .NET 3.0, 3.5 and 4.0 - without the 'ExtensionAttribute is defined in multiple places' warning.

Is there any compile time directive I can use to only include the ExtensionAttribute when the framework version being targetted is .NET 2?

6 Answers

Property groups are overwrite only so this would knock out your settings for DEBUG, TRACE, or any others. - See MSBuild Property Evaluation

Also if the DefineConstants property is set from the command line anything you do to it inside the project file is irrelevant as that setting becomes global readonly. This means your changes to that value fail silently.

Example maintaining existing defined constants:

    <CustomConstants Condition=" '$(TargetFrameworkVersion)' == 'v2.0' ">V2</CustomConstants>
    <CustomConstants Condition=" '$(TargetFrameworkVersion)' == 'v4.0' ">V4</CustomConstants>
    <DefineConstants Condition=" '$(DefineConstants)' != '' And '$(CustomConstants)' != '' ">$(DefineConstants);</DefineConstants>
    <DefineConstants>$(DefineConstants)$(CustomConstants)</DefineConstants>

This section MUST come after any other defined constants since those are unlikely to be set up in an additive manner

I only defined those 2 because that's mostly what I'm interested in on my project, ymmv.

See Also: Common MsBuild Project Properties

Related