Can I make a preprocessor directive dependent on the .NET framework version?

Dan Tao picture Dan Tao · Dec 26, 2010 · Viewed 12.3k times · Source

Here's a concrete example of what I want to do.

Consider the string.Join function. Pre-.NET 4.0, there were only two overloads, both of which required a string[] parameter.

As of .NET 4.0, there are new overloads taking more flexible parameter types, including IEnumerable<string>.

I have a library which includes a Join function that does essentially what the .NET 4.0 string.Join function does. I was just wondering if I could make this function's implementation dependent on the .NET framework being targeted. If 4.0, it could simply call string.Join internally. If 3.5 or older, it could call its own internal implementation.

  1. Does this idea make sense?
  2. If it does make sense, what's the most logical way to do it? I guess I'm just assuming a preprocessor directive would make the most sense, since a call to string.Join with an IEnumerable<string> parameter won't even compile when targeting a .NET version older than 4.0; so whatever approach I use would have to take place prior to compilation. (Checking the Environment.Version property at runtime, for example, wouldn't work.)

Answer

Joshua Rodgers picture Joshua Rodgers · Dec 26, 2010

You can take a look at another question on Stack Overflow that illustrates how to set conditional constants through the project file's XML: Detect target framework version at compile time

Then using that you can determine if you should use the .NET 4 overloads or your own library.