0

I am trying to call the public TryParse method via a dynamic object but I am getting a RuntimeBinderException... "System.Reflection.TypeInfo does not contain a definition for TryParse". The dynamic object at runtime has type System.Boolean and this class has that public method defined.

Note. Reason for this is to create a generic TryParse method with additional error checking that will be used repeatedly through the application.

Here's the code to reproduce the problem:

    private (bool Success, T Value) TryParse<T>(string strval)
    {
        (bool Success, T Value) retval;
        dynamic dtype = typeof(T);
        retval.Success = dtype.TryParse(strval, out retval.Value);
        return retval;
    }

In my case, I am testing the method with TryParse("true"). What am I doing wrong? Thanks.

markf78
  • 597
  • 2
  • 7
  • 25

1 Answers1

1

Bool.TryParse is a static method. Bool and typeof(Bool) are not the same thing. typeof(Bool) returns a System.Reflection.TypeInfo (which inherits from System.Type) object which has meta data about the boolean type, and does not have a method call TryParse.

You could use reflection to get the TryParse method from the type object

Type tType = typeof(T);
object[] args = { "true", false };
MethodInfo tryParseMethodInfo = tType.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public);
bool result = (bool)tryParseMethodInfo.Invoke(null, args);

But you might be better off using System.Convert. You could also look at using the approach described here

Jonathon K
  • 339
  • 2
  • 6
  • I was trying to avoid reflection. Thought (apparently incorrectly) dynamic might be a possible way. Leaning toward using Charlie Brown's answer on the link you provided in order to have a generic function that accomplishes TryParse + application specific error checking. – markf78 Aug 01 '19 at 03:30