Convert a Type to Reference Type

280 views Asked by At

I have a method that has a constraint like this:

public class MappingTransformation
{
    public static ClassMapped<T> Convert<T>(Mapping<T> source) where T : class
    {
        return ClassMapped<T>.GetInstance(source);
    }
}

This T MUST be reference type because it will be passed to EntityTypeConfiguration.

But, when consuming MappingTransformation.Convert<>(Mapping source) I only have a Type and don't know how to convert this Type into the needed "reference type".

Here is how I'm trying to consume it:

#region Test
        foreach (var item in mappingAssembly.GetTypes())
        {
            var mappingObj = Activator.CreateInstance(item);

            var modelName = mappingObj.GetType().GetProperty("ModelName").GetValue(mappingObj);

            var modelTypeEquivalent = modelAssembly.GetTypes().First(x => x.Name.Equals(modelName));

            var convertido = MappingTransformation.Convert<Model.Clientes>((Mapping<Model.Clientes>)mappingObj);


            var breakpoint = true;
        }
#endregion

How to achieve this?

2

There are 2 answers

1
SouthShoreAK On

I think I understand.

It looks like you want to define the type of your generic function at runtime, something like this?

        var modelTypeEquivalent = modelAssembly.GetTypes().First(x => x.Name.Equals(modelName));

        var convertido = MappingTransformation.Convert<modelTypeEquivalent >((Mapping<Model.Clientes>)mappingObj);

You want to find the type and then pass it as the type for your generic, is that right?

That's actually trickier than you might think. Types applied to generic functions and classes must be defined at compile time, not run time.

To do what you want, you'll need to use more reflection, see this related question for an example.

0
programad On

Never answer my own question before, but I think I got it. Still testing, but I think I got it.

Reading some other questions around Stack Overflow, I came to this:

#region Test
        foreach (var item in mappingAssembly.GetTypes())
        {
            var mappingObj = Activator.CreateInstance(item);

            var modelName = mappingObj.GetType().GetProperty("ModelName").GetValue(mappingObj);

            var modelTypeEquivalent = modelAssembly.GetTypes().First(x => x.Name.Equals(modelName));

            var convertionMethod = typeof(MappingTransformation).GetMethod("Convert");
            var genericConvertionMethod = convertionMethod.MakeGenericMethod(modelTypeEquivalent);
            var result = genericConvertionMethod.Invoke(null, new object[] { mappingObj });

            var breakpoint = true;
        }
#endregion

This was the question that lead me to the answer from Mr. Jon Skeet.