using System.Globalization;
using System.ComponentModel;
public static void Main()
DateTime? result = Convert<DateTime?>("2024-02-02 16:20:00.0000000");
Console.WriteLine(result);
public static T? Convert<T>(object? instance)
return (T)Enum.Parse(typeof(T), instance.ToString());
if (typeof(T) == typeof(Uri))
Uri uriValue = new Uri(instance.ToString(), UriKind.RelativeOrAbsolute);
return (T)System.Convert.ChangeType(uriValue, typeof(T), CultureInfo.CurrentCulture);
if (instance is IConvertible convertible)
Console.WriteLine("Issue is here");
return (T)System.Convert.ChangeType(convertible, typeof(T), CultureInfo.CurrentCulture);
if (typeof(T).IsAssignableFrom(instance.GetType()))
TypeConverter converter = TypeDescriptor.GetConverter(instance);
if (converter.CanConvertTo(typeof(T)))
return (T)converter.ConvertTo(instance, typeof(T));
throw new InvalidCastException("Invalid cast to '{0}'.");