Is there any generic Parse() function that will convert a string to any type using parse?

C#StringParsingType Conversion

C# Problem Overview


I want to convert a string to a generic type like int or date or long based on the generic return type.

Basically a function like Parse<T>(String) that returns an item of type T.

For example if a int was passed the function should do int.parse internally.

C# Solutions


Solution 1 - C#

System.Convert.ChangeType

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 - C#

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 - C#

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 - C#

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.

Solution 5 - C#

There are a couple of conventions in the .NET to convert objects of one type to another.

But these methods are much slower than your typical T.Parse(string), cause boxing and involve lots of allocations each time you want to convert a single value.

For ValueString, I chose to find a suitable, static parsing method of the type using reflection, build a lambda expression calling it and cache the compiled delegate for future use (See this answer for an example).

It also fallbacks to the ways I mentioned above if the type doesn't have a suitable parsing method (See the performance section in the readme).

var v = new ValueString("15"); // struct
var i = v.As<int>(); // Calls int.Parse.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKarimView Question on Stackoverflow
Solution 1 - C#AniView Answer on Stackoverflow
Solution 2 - C#Pranay DeepView Answer on Stackoverflow
Solution 3 - C#EonasdanView Answer on Stackoverflow
Solution 4 - C#Alex SiepmanView Answer on Stackoverflow
Solution 5 - C#Şafak GürView Answer on Stackoverflow