Im trying to make a universal parser using generic type parameters, but i can't grasp the concept 100%
private bool TryParse<T>(XElement element, string attributeName, out T value) where T : struct
{
if (element.Attribute(attributeName) != null && !string.IsNullOrEmpty(element.Attribute(attributeName).Value))
{
string valueString = element.Attribute(attributeName).Value;
if (typeof(T) == typeof(int))
{
int valueInt;
if (int.TryParse(valueString, out valueInt))
{
value = valueInt;
return true;
}
}
else if (typeof(T) == typeof(bool))
{
bool valueBool;
if (bool.TryParse(valueString, out valueBool))
{
value = valueBool;
return true;
}
}
else
{
value = valueString;
return true;
}
}
return false;
}
As you might guess, the code doesn't compile, since i can't convert int|bool|string to T (eg. value = valueInt). Thankful for feedback, it might not even be possible to way i'm doing it. Using .NET 3.5
The XElement and XAttribute classes both provide a set of explicit conversion operators (casts) to conveniently convert their contents to .NET primitive types.
For example, you can simply do:
XElement elem = // ...
string value1 = (string)elem.Attribute("myString");
int value2 = (int)elem.Attribute("myInt");
int? value3 = (int?)elem.Attribute("myOptionalInt");
bool value4 = (bool)elem.Attribute("myBool");
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