EDIT: I've done some research about this, but have not been able to find a solution!
I'm reading a configuration from an XML file. The layout of the configuration is set for certain version. This version is in the first line of the XML, which is easy to extract.
What I would like to know is, what is the best way to actually parse this file/get another method, based on the version (so all 4 elements, the Major, Minor, Build and Revision).
Right now I've come up with this:
switch (version.Major)
{
case 0:
switch (version.Minor)
{
case 0:
switch (version.Build)
{
case 0:
switch (version.Revision)
{
case 0:
return VersionNone(doc);
}
break;
}
break;
}
break;
}
throw new NotImplementedException();
But I do not find this elegant (at all) and I feel like there is a way better way to do this.
Anyone who can help?
For something like this i'd be tempted to build a dictionary of actions
Edit: Updated to include a document paramter in response to comment from OP
Dictionary<string, Action<XmlDocument>> versionSpecificMethods = new Dictionary<string, Action<XmlDocument>>{
{"1.0.0.0", DoStuff1},
{"1.2.3.4", DoStuff2},
{"3.1.7.182", DoStuff3}};
private void RunMethodForVersion(string version, XmlDocument someXmlDoc)
{
var codeToRun = versionSpecificMethods[version];
codeToRun.Invoke(someXmlDoc);
}
private static void DoStuff1(XmlDocument doc)
{
// Insert user code here
}
If you want to share code between version, you can try to use inheritance:
interface IConfig
{
string GetConnectionString();
string GetUserSettings();
int GetDelay();
}
class Version_1 : IConfig
{
public virtual string GetConnectionString() { ... }
public virtual string GetUserSettings { ... }
public virtual int GetDelay();
}
class Version_1_1 : Version_1
{
// Changed UserSetttings and delay in xml
public override GetUserSettings { ... }
public override int GetDelay { ... }
}
class Version_1_1_4 : Version_1_1
{
// Changed delay in xml
public override int GetDelay { ... }
}
Now you need create reqired instance of config depend on version of your file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With