Brent
Brent

Reputation: 4876

What does the class type constraint achieve if a generic type constraint must also implement an interface in c#

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

Upvotes: 1

Views: 55

Answers (2)

Tom Chantler
Tom Chantler

Reputation: 14931

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
}

Upvotes: 2

Christos
Christos

Reputation: 53958

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.

Upvotes: 1

Related Questions