Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IsGenericType & IsValueType missing from .Net Core?

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

enter image description here

like image 379
LP13 Avatar asked Aug 26 '16 14:08

LP13


1 Answers

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);
    }
}
like image 55
Venky Avatar answered Nov 02 '22 14:11

Venky