Is there any generic Parse() function that will convert a string to any type using parse?
Solution 1
As per your example, you could do:
int i = (int)Convert.ChangeType("123", typeof(int));
DateTime dt = (DateTime)Convert.ChangeType("2009/12/12", typeof(DateTime));
To satisfy your "generic return type" requirement, you could write your own extension method:
public static T ChangeType<T>(this object obj)
{
return (T)Convert.ChangeType(obj, typeof(T));
}
This will allow you to do:
int i = "123".ChangeType<int>();
Solution 2
Well looks like I am too late for answering on this thread. But here is my implementation:
Basically, I have created an Extention method for the Object class. It handles all the types, i.e nullable, classes, and struct.
public static T ConvertTo<T>(this object value)
{
T returnValue;
if (value is T variable)
returnValue = variable;
else
try
{
//Handling Nullable types i.e, int?, double?, bool? .. etc
if (Nullable.GetUnderlyingType(typeof(T)) != null)
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
returnValue = (T) conv.ConvertFrom(value);
}
else
{
returnValue = (T) Convert.ChangeType(value, typeof(T));
}
}
catch (Exception)
{
returnValue = default(T);
}
return returnValue;
}
Solution 3
cleaner version of Pranay's answer
public static T ConvertTo<T>(this object value)
{
if (value is T variable) return variable;
try
{
//Handling Nullable types i.e, int?, double?, bool? .. etc
if (Nullable.GetUnderlyingType(typeof(T)) != null)
{
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(value);
}
return (T)Convert.ChangeType(value, typeof(T));
}
catch (Exception)
{
return default(T);
}
}
Solution 4
System.Convert.ChangeType
does not convert to any type. Think of the following:
- nullable types
- enums
- Guid etc.
These conversions are possible with this implementation of ChangeType.
Related videos on Youtube
Karim
Updated on August 26, 2020Comments
-
Karim over 3 years
I want to convert a string to a generic type like
int
ordate
orlong
based on the generic return type.Basically a function like
Parse<T>(String)
that returns an item of typeT
.For example if a int was passed the function should do
int.parse
internally. -
Karim over 13 yearscool , but the strange thing its named ChangeType , so i would thought that this function does some kind of cast and not parse
-
Ani over 13 yearsMSDN says it is simply a wrapper that finds the right conversion method on the source object, requiring that it implements the IConvertible interface.
-
Liam over 8 yearsIf it needs to implement
IConvertable
shouldn't you also constrain theT
, i.e.T ChangeType<T>(this object obj) where T : IConvertable
? -
Ani over 8 years@Liam: No, it's
obj
that must beIConvertible
, but there's no way to specify that at compile-time. -
Hopeless over 8 yearsif I need something like TryChangeType that returns null or false in fail case? Only by catching exception?
-
Ole Albers about 6 yearsIMHO this is the better answer cause it also contains the "nullable"-aspect
-
Luke T O'Brien about 5 yearsI am doing exactly this in my code.... The trouble is is won't cast
1
as a boolean. Is there a generic way of handling all value types -
IMujagic over 4 yearsis there a specific reason why you are using
TypeDescriptor
for nullable types andConvert.ChangeType
for non-nullable ones? This wholetry
block can be reduced only toTypeConverter
2 lines of code and it will work for both, nullable and non-nullable.