How to invoke function output parameter and reflection? (TryParse Generic) RRS feed

  • Question

  • I would like to call TryParse Method with generic types

    But after invoke I became a NULL in output variable.

    Why and how can I achive this goal?


    // this class has a property Date // became a property var propertyclass = this.GetType().GetProperty("Date"); // became a property type Type T = propertyclass.PropertyType; // create a variable of property type for output object ores = Activator.CreateInstance(T); // became a method TryParse of type of property var method = T.GetMethod("TryParse", new[] { typeof(string), T.MakeByRefType() }); // call method with parameters var result = (bool)method.Invoke(null, new object[] { "01.01.2020", ores }); // get result THE PROBLEM: ores is null if (result) { propertyclass.SetValue(this, ores, null); }

    Friday, March 13, 2020 9:00 AM

All replies

  • That's work!

    var propertyclass = this.GetType().GetProperty("Date"); Type T = propertyclass.PropertyType; object[] args = { "01.01.2020", null }; var method = T.GetMethod("TryParse", new[] { typeof(string), T.MakeByRefType() });// , BindingFlags.Public | BindingFlags.Static); var result = (bool)method.Invoke(null, args); if (result) { propertyclass.SetValue(this, args[1], null); }

    Make IT better.

    Friday, March 13, 2020 9:21 AM
  • Tried the following and it works here:

            public DateTime Date { get; set; }
            public Class1()
                var pClass = GetType().GetProperty(nameof(Date));
                var pType = pClass?.PropertyType;
                var obj = Activator.CreateInstance(pType);
                var method = pType.GetMethod("TryParse", new[] {typeof(String), pType.MakeByRefType()});
                var dateString = "2020/03/13";
                var result = (Boolean) method.Invoke(null, new[] {dateString, obj});
                if (result)
                    pClass.SetValue(this, obj, null);

    Friday, March 13, 2020 9:32 AM
  • Hi Interraptor,
    I am glad you have got your solution,we suggest that you mark it as the answer. So it can help other people who have the same problem find a solution quickly.
    Best Regards,
    Daniel Zhang

    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Monday, March 16, 2020 8:16 AM