0

And let me say at the outset, that I know about the 'PropertyType' property.

So I've been working with a generic converter.

Usage is pretty simple; it looks like this:

int1 = TConverter.ChangeType<int>(strt1);

So that string becomes and int (if it can). And the above works fine. The problem, however, is that part between the angular brackets where the type is listed. I want to get the type of a PropertyInfo in there, but I can't see to.

The code, which I have simplified down to the main issue, looks like this:

foreach (PropertyInfo pi in props)
        {
            Type tp = pi.PropertyType;

            var converted = TConverter.ChangeType<tp>("Test");
        }

I guess I must be making a mistake because it has a problem with the contents of the angular brackets. I get this message: "Error 2 The type or namespace name 'tp' could not be found (are you missing a using directive or an assembly reference?)"

Can someone offer a solution?

  • Looks like you are trying to do this: https://stackoverflow.com/questions/5961816/c-sharp-generic-method-and-dynamic-type-problem – Creyke Aug 22 '18 at 14:17
  • When you are writing code as the *consumer* of generics, you need to know the types you're supplying at your *compile* time (indeed, at compile time, the compiler has to decide the type of `converted`, because that's what `var` means). That means you need to supply compile-time types or be generic yourself and pass through some of *your* type parameters. – Damien_The_Unbeliever Aug 22 '18 at 14:19

1 Answers1

0

You have to build an instance of the generic method dynamically:

MethodInfo openChangeType = typeof(TConverter).GetMethod(nameof(TConverter.ChangeType));
MethodInfo closedChangeType = method.MakeGenericMethod(tp);
closedChangeType.Invoke(obj: null, "Test");
vc 74
  • 37,131
  • 7
  • 73
  • 89