Reputation: 930
I'm writing a program that's working with external data, which I can't control. This data changes over time, but I want my program to be compatible to various versions of it. In other languages I'd use #define to specify the version, and than use #if, to do the necessary things for the specified version. Like
#if VERSION >= 5
...
#endif
I know this isn't possible in C#, since it only allows to define symbols, but not assign something to them. So I'm wondering, what's the best way to accomplish this? I could define things like VERSION_5, but I'd rather be able to check specific versions, and especially ranges, which would be annoying like this. The next best thing I can think of is const, but that would have to be checked on run-time, which might slow down things a tiny little bit. I'm not sure if it would even be noticeable in my project, but I'm worried about it.
Is there a standard way to do this in C#? What's the best way?
Upvotes: 0
Views: 669
Reputation: 2500
I'm writing a program that's working with external data, which I can't control.
So while it's a server application, you may recieve data formatted with any version, then, you have to support all. In result, you should not make compile time decisions via directives, you should analyze data runtime for a supported pattern and continue the suitable processing after recognizing the pattern. For example run different threads for different versions then recognizer should pass the recognized data to responsible suitable threads in parallel and also fail unknown data!
Upvotes: 0
Reputation: 20366
This example is .NET version dependent. For some projects, they use
#if NET_2_0
...
#endif
#if NET_3_5
...
#endif
#if NET_4_0
...
#endif
#if NET_4_5
...
#endif
At the end of the lifecycle for .NET 1.1, they simply remove NET_2_0 conditionals in order to maintain less conditionals.
In project file for .NET 4.5, define NET_2_0, NET_3_5, NET_4_0, NET_4_5
In project file for .NET 4.0, define NET_2_0, NET_3_5, NET_4_0
In project file for .NET 3.5, define NET_2_0, NET_3_5
In project file for .NET 2.0, define NET_2_0
In project file for .NET 1.1, no define symbol
Upvotes: 0
Reputation: 174289
I would create one or multiple interfaces for the data processing. Each interface gets potentially implemented multiple times, once per version range. These interface implementations than get injected into the class that handles the data.
Something like this:
public interface IDataProcessor
{
void Process(Data data);
bool SupportsVersion(int version);
}
In the data handler class:
foreach(var dataProcessor in _dataProcessors)
{
if(dataProcessor.SupportsVersion(versionOfCurrentData))
{
dataProcessor.Process(data);
}
}
Upvotes: 1