views:

30

answers:

1

Hi. I have a generic abstract base class from which I would like to derive from a dynamic type built through reflection.emit. Also I need to customize the derived class default constructor to initialize some fields. To build the default constructor of the derived class correctly I need to obtain the default constructor of the base class and invoke it. The problem is that I'm not being able to get the default constructor from the base class.

An example:

public abstract class Test<T>
{
    private T data;

    public abstract void Go();
}

public class TestDerive : Test<int>
{
    public override void Go()
    {
    }
}

class Program
{
    static void Main(string[] args)
    {
        ConstructorInfo[] constructors = typeof(Test<>).GetConstructors();

        int length = constructors.Length;
    }
}

I've tried everything and length is always zero. I don't understand. I've inspected similar cases in the reflector and there's indeed a call to the base constructor of the abstract class. The question is how do I get it to do the same ?

+4  A: 

The default constructor of an abstract class is protected - you need to specify binding flags to access it via reflection. You can use

typeof(Test<>).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)

(It makes no practical difference whether it's public or protected in normal code, of course, as you can't call the constructor other than from a derived type.)

Note that this is the case whether or not the class is generic - it's the abstractness that's causing you problems.

Jon Skeet
Thanks a lot. That's it
Ivo Leitão