I am trying to write a class to parse a XML config file with value strings to the corresponding values and type. An example entry of the config would be:
<ConfigItem Name="ParameterName" Value="1.3" Type="Double"/> I now would like to write a function to parse my value, so that I can do something like this:
double value = GetItemValue("//ConfigItem[@Name='ParameterName']"); Initially I tried overloading GetItemValue with its return type, but this is not possible in C#. I now tried using a generic function so that I would do:
double value = GetItemValue<double>("//ConfigItem[@Name='ParameterName']"); The function I tried to write is something like this:
public T GetItemValue<T>(string configName) { list = XmlConfig.SelectNodes(configName); T returnValue; if (T.TryParse(list[0].Attributes["Value"].Value, out returnValue)) return returnValue; else throw new InvalidProgramException("Could not parse: " + configName); } Unfortunately this does not work and I am getting the following error:
Error CS0119 'T' is a type parameter, which is not valid in the given context I am not sure what the problem is, but I suspect, it has to due with the fact, that it is not clear at compile time, whether all types T will have the method TryParse. I tried working around this by using a constraint like where T : Int, Double, but C# contraints do not support ValueTypes.
So what is the problem and how can I achieve, what I am trying to do? Please note for any suggestions that in the future I will also have to custom types for T.
int.TryParse()for yourT.TryParse()method, you may have a bug.int.TryParse()parses numbers using the formatting information in a NumberFormatInfo object initialized for the current system culture. However, XML is conventionally culture-independent. I'd recommend using culture-independent methods, or methods fromXmlConvert.