Home > front end >  C# Generic Type Function, Make Generic Method Fails with System.String
C# Generic Type Function, Make Generic Method Fails with System.String

Time:09-17

I'm using .net Core 5.0.302 and having trouble using Reflection to invoke a generic method

The function is

public static T Parse<T>(List<Token> tokenList, int startPos) where T : new(){
            if(tokenList[startPos].tokenData.ToString() == "["){
                // ParseArray(tokenList);
                throw new NotImplementedException();
            }
            else if(tokenList[startPos].tokenData.ToString() == "{"){
                return ParseObject<T>(tokenList, startPos);
            }else{
                T retVal = new T();
                retVal = (T)tokenList[startPos].tokenData;
                return retVal;
            }
        }

The code that is attempting to invoke this method is here -

MethodInfo method = typeof(JsonParser).GetMethod(nameof(JsonParser.Parse), BindingFlags.Static | BindingFlags.Public);
                            method = method.MakeGenericMethod(typeof(string));
                            object parsedType = method.Invoke(null, new object[]{tokenList, i   3});
                            props[z].SetValue(typeInst, parsedType);

And this is the error message I'm receiving

System.Security.VerificationException : Method ParseLib.JsonParser.Parse: type argument 'System.String' violates the constraint of type parameter 'T'. Stack Trace: at System.RuntimeType.ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e) at System.Reflection.RuntimeMethodInfo.MakeGenericMethod(Type[] methodInstantiation) at ParseLib.JsonParser.ParseObject[T](List1 tokenList, Int32 startPos) in /home/user/Projects/MyProjects/JsonParseSharp/ParseLib/JsonParser.cs:line 54 at ParseLib.JsonParser.Parse[T](List1 tokenList, Int32 startPos) in /home/user/Projects/MyProjects/JsonParseSharp/ParseLib/JsonParser.cs:line 15 at ParseTests.JsonParserTest.TestParseBasicObject() in /home/user/Projects/MyProjects/JsonParseSharp/ParseTests/JsonParserTest.cs:line 16 ----- Inner Stack Trace ----- at System.RuntimeMethodHandle.GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation) at System.Reflection.RuntimeMethodInfo.MakeGenericMethod(Type[] methodInstantiation)

Haven't been able to figure out why System.String violates the type parameter 'T' if I replace typeof(string) with typeof(int), everything works as expected. Does anyone have any idea what might be the issue here?

Thanks in advance!

CodePudding user response:

where T : new()

Your Parse method has a type constraint that indicates that type T must have a public parameterless constructor.

in c#, the string constructor requires at least one parameter to construct a string.

var str = new string("abc")

But the int can be instantiated using a parameterless constructor:

var num = new int()

  • Related