So here is what I am trying to do.
I create a generic class that allocates the type specified by the generic parameter in one of two ways, determined by using the overloaded constructor.
Here is an example:
class MyClass<T> where T : class { public delegate T Allocator(); public MyClass() { obj = new T(); } public MyClass( Allocator alloc ) { obj = alloc(); } T obj; }
This class requires that type T be reftype in all cases. For the default constructor, we want to instantiate T through its default constructor. I would like to put where T : new() in my default constructor, for example:
public MyClass() where T : new() { obj = new T(); }
However, this is not valid C #. Basically, I only want to add a restriction on the type T to have a default constructor only when the default constructor MyClass () is used.
In the second constructor of MyClass, we allow the user to determine how to distribute their own distribution method for T, so it is obvious that MyClass makes sense not to use T in all cases by default.
I have a feeling that for this I need to use reflection in the default constructor, but I hope not.
I know this can be done because the Lazy<T> class in .NET 4.0 does not require T to be constructive by default at the class level, but it does have constructors similar to those shown in my example. I would like to know how Lazy<T> does this at least.
generics c #
void.pointer
source share