Inherit from a generic base class, apply a constraint, and implement an interface in C#
You include the entire signature of your class before you define generic constraints.
class DerivedFoo<T1, T2> : ParentFoo<T1, T2>, IFoo where T2 : IBar
{
...
}
My recommendation: when you have a question about the syntax of the C# language, read the specification; that's why we publish it. You'll want to read section 10.1.
To answer your specific question, the order of things in a class declaration is:
- attributes, in square brackets
- modifiers ("public", "static", and so on)
- "partial"
- "class"
- the class name
- a comma-separated list of type parameter declarations inside angle brackets
- a colon followed a comma-separated list of base types (base class and implemented interfaces, base class must go first if there is one)
- type parameter constraints
- the body of the class, surrounded by braces
- a semicolon
Everything on that list is optional except for "class", the name, and the body, but everything must appear in that order if it appears.
public interface IFoo {}
public interface IBar {}
public class ParentFoo<T,T1> { }
public class DerivedFoo<T, T1> : ParentFoo<T, T1>, IFoo where T1 : IBar { }
public class KeyAndValue<T>
{
public string Key { get; set; }
public virtual T Value { get; set; }
}
public class KeyAndValue : KeyAndValue<string>
{
public override string Value { get; set; }
}
This is an extension off the existing answers. It defaults to string
if you don't supply a type. I didn't implement an interface but that shouldn't require anything different than usual.