Generics, constrains and inheritance

J

Joe

Hi All!

Here's the problem I'm having. I want to create a generic class that
inherits from CollectionBase and implements IBindingList. As part of
IBindingList I have to implement AddNew(). Since this is a generic class the
new throws an error "Cannot create an instance of the variable type 'T'
because it does not have the new constraint".

How do I add a constraint to my class and be able to keep the CollectionBase
and IBindingList?

When I add the where <T>: it means that I want the class T to implement
CollectionBase and IBindingList.

Is it possible to do what I want?

Thanks,
Joe
 
J

Joe

I believe I have my answer. I need to declare my class like this:

class MyClass<T> : CollectionBase, IBindingList where T: new ()
{
....
}
 
P

puzzlecracker

I believe I have my answer. I need to declare my class like this:

class MyClass<T> : CollectionBase, IBindingList where T: new ()
{
    ....

}
I don't think compiler knows what t where T: new () means...
 
B

Ben Voigt [C++ MVP]

puzzlecracker said:
I should have rtfm'ed. I didn't know that you can constrain types
based on different constructor types... learn something new every
day...

You can't. At least not the part about different constructor types. There
is a constraint for "public parameterless constructor" and that's it, sadly.
 

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