Inherit from a base base class, apply a constraint, and implement an interface in C #

This is a syntax question. I have a generic class that inherits from a generic base class and applies a constraint to one of the type parameters. I also want the derived class to implement the interface. For my life, I cannot understand the correct syntax.

This is what I have:

DerivedFoo<T1,T2> : ParentFoo<T1, T2> where T2 : IBar { ... } 

The first thing that came to mind was the following:

 DerivedFoo<T1,T2> : ParentFoo<T1, T2> where T2 : IBar, IFoo { ... } 

But this is not true, because it leads to the fact that T2 needs to implement both IBar and IFoo, and not DerivedFoo to implement IFoo.

I tried a bit of googling, using colons, semicolons, etc., but I ended up short. I am sure the answer is dizzyingly simple.

+58
generics inheritance c # interface constraints
Jan 05 '10 at 16:28
source share
3 answers

Before defining common constraints, you include the entire signature of your class.

 class DerivedFoo<T1, T2> : ParentFoo<T1, T2>, IFoo where T2 : IBar { ... } 
+97
Jan 05 '10 at 16:30
source share

My recommendation: when you have a question about the syntax of the C # language, read the specification; why we publish it. You want to read section 10.1.

To answer your specific question, the order of things in the class declaration:

  • in square brackets
  • ("public", "static", etc.)
  • "partial"
  • "class"
  • class name
  • comma separated list of type parameter declarations inside angle brackets
  • the colon follows a comma-separated list of base types (base class and implemented interfaces, the base class should go first, if any)
  • type parameter restrictions
  • class body surrounded by braces
  • semicolon

Everything in this list is optional except for the "class", name, and body, but everything should appear in that order if it appears.

+14
Jan 05 '10 at 17:43
source share
 public interface IFoo {} public interface IBar {} public class ParentFoo<T,T1> { } public class DerivedFoo<T, T1> : ParentFoo<T, T1>, IFoo where T1 : IBar { } 
+6
Jan 05 '10 at 16:32
source share



All Articles