Jonathan Jonathan - 11 months ago 85
C# Question

Use reflection/generics to generate wrapper class

I'd like to create a wrapper class dynamically, such that for every desired class (probably underneath a certain namespace like DBO) I'll get an appropriate class like this:

public class [ClassName]Wrapper{
public [ClassName] [ClassName] { get; set; }

Second, I need to if based on wrapper vs original type. I'm assuming I can just do something like:

(classBob as Type).ToString().EndsWith("Wrapper")

If I require anything more, please help me out :).

I'm fairly new to reflection and I've never built a class at runtime. Code to do this would be great, but even pointing out excellent resources to study up on the tools used to do this would be a great move forward for me.


Answer Source

Wouldn't using generics solve your problem?

public class Wrapper<T>
    where T : class
    public Wrapper(T wrappee)
        Class = wrappee;

    public T Class { get; } // C# 6.0 Syntax, otherwise add "private set;"

Then you can create a wrapper at runtime with

Type typeToBeWrapped = objToBeWrapped.GetType();

Type genericWrapper = typeof(Wrapper<>);
Type constructedWrapper = genericWrapper.MakeGenericType(typeToBeWrapped);
object obj = Activator.CreateInstance(constructedWrapper, objToBeWrapped);