I have this code in .Net 4.6.2 and now trying to convert into .Net core however I am getting error
Error CS1061 'Type' does not contain a definition for 'IsGenericType' and no extension method 'IsGenericType' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)
public static class StringExtensions
{
public static TDest ConvertStringTo<TDest>(this string src)
{
if (src == null)
{
return default(TDest);
}
return ChangeType<TDest>(src);
}
private static T ChangeType<T>(string value)
{
var t = typeof(T);
// getting error here at t.IsGenericType
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return default(T);
}
t = Nullable.GetUnderlyingType(t);
}
return (T)Convert.ChangeType(value, t);
}
}
What is equivalent in .Net Core?
Update1
Surprisingly when I debug the code I see variable t
has IsGenericType
property however I cannot use IsGenericType
in the code. Not sure why or which namespace I need to add. I have added using System
and using System.Runtime
both namespaces
Yes, They are moved in .Net Core to a new TypeInfo
class. The way to get this working is by using GetTypeInfo().IsGenericType
& GetTypeInfo().IsValueType
.
using System.Reflection;
public static class StringExtensions
{
public static TDest ConvertStringTo<TDest>(this string src)
{
if (src == null)
{
return default(TDest);
}
return ChangeType<TDest>(src);
}
private static T ChangeType<T>(string value)
{
var t = typeof(T);
// changed t.IsGenericType to t.GetTypeInfo().IsGenericType
if (t.GetTypeInfo().IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return default(T);
}
t = Nullable.GetUnderlyingType(t);
}
return (T)Convert.ChangeType(value, t);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With