1

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)?

Torsten Crull
  • 123
  • 3
  • 9
  • I would create a [Code Snippet](https://msdn.microsoft.com/en-us/library/z41h7fat.aspx) for the boiler plate code. Also see:[How to: Create a New Snippet with Replacements](https://msdn.microsoft.com/en-us/library/ms165396.aspx). – TnTinMn Apr 12 '17 at 23:12
  • @TnTinMn: Good idea, if you're not in a project phase of 'concept', where you want to get a decision and you want to try several variants. – Torsten Crull Apr 12 '17 at 23:18
  • If you need dynamic code generation to quickly evaluate alternatives, then it may be worth the trouble to set up a T4 template. See: [Design-Time Code Generation by using T4 Text Templates](https://msdn.microsoft.com/en-us/library/dd820620.aspx). This is basically a pre-processing step to generate a code file. – TnTinMn Apr 13 '17 at 00:08
  • Thanks! I did not kow **4 Text Templates** until now. Looking for other solutions I found **Roslyn CTP** in this answer: [Custom language features in C#](http://stackoverflow.com/a/11749422/3303008) – Torsten Crull Apr 13 '17 at 14:47

1 Answers1

2

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

Selman Genç
  • 100,147
  • 13
  • 119
  • 184