Generic type parameters using out
- by Mikael
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