C# Generic with Constraint, Custom Constructor?

G

gilbert@gmail

Hello.

I am trying to use c# generic to define a class.

class MyClass<T> where T: new(){

}

In this definition, MyClass can create T objects with a default
constructor. Is there any way to set the constraint such that MyClass
can create T objects with some custom constructors (provided that T
has such a cstr)?



Thank you very much!

Gilbert
 
C

Chris Mullins [MVP - C#]

I don't believe there is - at least not that I've ever seen.

The obvious workaround is to constrain your classes to be "IGilbertable",
and have that interface define whatever signature you need:

public Interface IGilbertable
{
void Initialize(List<string> endpoints);
IGilbertable CreateInstance(List<string> endpoints);
}
 
N

Nicholas Paldino [.NET/C# MVP]

Gilbert,

Unfortunately, no, there isn't. The default constructor constraint is
the only one.

You could use reflection in the static constructor to check the type
parameter to see if it has the constructor that you require, but this has
the side effect of not giving you a compile-time check, just a run-time
check.

If you don't need a specific constructor, rather, if you can have an
initializer method, then I would create an interface with that method, and
implement it on your classes (if you can). Either that, or create an
interface which will act as a class factory, with one method with the
parameters you need. Then, you can have implementations of that class which
will create the classes. Something like this:

interface IPersonFactory<T>
{
public T Create(string name, int age);
}

class Person
{
public string Name;
public int Age;
}

class PersonFactory : IPersonFactory<Person>
{
public Person Create(string name, int age)
{
Person retVal = new Person();
retVal.Name = name;
retVal.Age = age;

return retVal;
}
}

class PersonUtils<TFactory, TPerson> where TFactory : IPersonFactory
{
}

This way, you can have a class which will construct the instances you
need, which implements a factory interface which you can use in whatever
class you were going to make generic in the first place.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top