Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Can a generic class implement an interface?

Only generic classes can implement generic interfaces. Normal classes can't implement generic interfaces.

Can we inherit from generic class?

You cannot inherit a generic type. // class Derived20 : T {}// NO!

What does the generic constraint of type interface do?

Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.

Can generic classes be constrained?

Declaring those constraints means you can use the operations and method calls of the constraining type. If your generic class or method uses any operation on the generic members beyond simple assignment or calling any methods not supported by System. Object, you'll apply constraints to the type parameter.


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.