1

When writing generic methods and functions, I have seen the Where type constraint written as

public static void MyMethod<T>(params T[] newVals) where T : IMyInterface

and also

public static void MyMethod<T>(params T[] newVals) where T : class, IMyInterface

does the 'class' type constraint add anything - I don't imagine a struct could ever implement an interface, but i could be wrong?

Thank you

Brent
  • 4,611
  • 4
  • 38
  • 55

2 Answers2

2

A struct can implement an interface, so it's quite reasonable to have the double constraint of requiring the generic type T to be both a class and to implement the specified interface.

Consider this from Dictionary:

[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Enumerator : 
    IEnumerator<KeyValuePair<TKey, TValue>>, IDisposable, 
    IDictionaryEnumerator, IEnumerator
{
    //  use Reflector to see the code
}
Tom Chantler
  • 14,753
  • 4
  • 48
  • 53
1

Structs can implement interfaces. So this

where T : class, IMyInterface

demands both the type T be a class and a class which implements the interface called IMyInterface.

For instance this is the declaration of Int32 structure:

[SerializableAttribute]
[ComVisibleAttribute(true)]
public struct Int32 : IComparable, IFormattable, 
                      IConvertible, IComparable<int>, IEquatable<int>

as you can see here.

Christos
  • 53,228
  • 8
  • 76
  • 108