I've come across this problem often, but I haven't found a satisfying solution yet.
I am implementing a reader for savegames (but it could also be applied to other types of files). Depending on the version, there are some added entries, but the order always remains the same. Therefore I created a class:
public class Entry<T> {
public T Value;
public readonly FileVersion MinVersion;
public Entry(T v = default(T), ScenarioVersion m = FileVersion.V115) {
Value = v;
MinVersion = m;
}
}
Now, you guess, I want to write those entries with as less code as possible. I want to write the line if (version >= MinVersion) { /* write data */ }
only once. The Entries can be primitive types or objects, which is the problem...
Should define an interface and implement it for every needed primitive type as a wrapper? Or is there a more elegant solution?