Reputation: 11990
I am trying to write a generic function in c# which tries to parse a string based on the type.
Here is what I tried
public static T convertString<T>(string raw)
{
if( typeof(T) == DateTime ){
DateTime final;
DateTime.TryParseExact(raw, "yyyy-mm-dd hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out final);
return final;
}
if( typeof(T) == int ){
int final;
Int32.TryParse(raw, out final);
return final;
}
}
How can I correct this function to work?
Upvotes: 3
Views: 1495
Reputation: 1041
You can even do this more generic and not rely on a string parameter provided the type U implements IConvertible - this means you have to specify two type parameters though:
public static T ConvertValue<T,U>(U value) where U : IConvertible
{
return (T)Convert.ChangeType(value, typeof(T));
}
Upvotes: 0
Reputation: 29492
you can try something like that :
public static T ConvertFromString<T>(string raw)
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(raw);
}
// Usage
var date = ConvertFromString<DateTime>("2015/01/01");
var number = ConvertFromString<int>("2015");
Edit: Support for TryConvert
Otherwise you can create a function that will try to convert the input string:
public static bool TryConvertFromString<T>(string raw, out T result)
{
result = default(T);
var converter = TypeDescriptor.GetConverter(typeof (T));
if (!converter.IsValid(raw)) return false;
result = (T)converter.ConvertFromString(raw);
return true;
}
// Usage
DateTime result;
if (!TryConvertFromString<DateTime>("this is not a date", out result))
{
}
Upvotes: 4