Torsten Crull
Torsten Crull

Reputation: 133

How to define constraint for generic interface where-clause

C# has no preprocessing and I don't want to define "struct, IComparable, IFormattable, IConvertible" for all interfaces, that need this constraint. What I need is something like:

Named constraint "IMyItemConstraint" for several generic interface where-clauses:

public interface IProperty2Enum<T>
    : IEnumerable<T>
    where T : IMyItemConstraint { } // <--- here

public interface IMyCollection2<T>
    : IEnumerable<T>, INotifyCollectionChanged, INotifyPropertyChanged 
    where T : IMyItemConstraint { } // <--- here

public interface IMyObservableCollection2<T>
    : IEnumerable<T>, INotifyCollectionChanged, INotifyPropertyChanged 
    where T : IMyItemConstraint { } // <--- here

I tried to define a name "IMyItemConstraint", but I get errors CS####:

public interface IMyItemConstraint 
    : struct, IComparable, IFormattable, IConvertible { } // CS1031: Type expected 

public interface IMyItemConstraint : where IMyItemConstraint
    : struct, IComparable, IFormattable, IConvertible { } // CS1031: Type expected 

public interface IMyItemConstraint<T> where T // This does not help:
    : struct, IComparable, IFormattable, IConvertible { }

Is it possible, to define a named constraint for generic interface where-clause for several interfaces (contracts)?

Upvotes: 1

Views: 876

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101742

Unfortunutely you can't inherit generic constraints. You need to define constraints separately for each type parameter.

Upvotes: 2

Related Questions