github twitter email rss
.Net C# Generics Constraints
0001 Jun 1
2 minutes read

.Net C# Generics Constraints

Primary Constraints

internal sealed class PrimaryConstraintOfStream<T> where T : Stream {
    public void M(T stream) {
        stream.Close();// OK
    }
}

internal sealed class PrimaryConstraintOfClass<T> where T : class {
    public void M() {
        T temp = null; // Allowed because T must be a reference type
    }
}

internal sealed class PrimaryConstraintOfStruct<T> where T : struct {
    public static T Factory() {
        // Allowed because all value types implicitly
        // have a public, parameterless constructor
        return new T();
    }
}

Secondary Constraints

public static class SomeType {
    private static void Test() {
        Int32 x = 5;
        Guid g = new Guid();
        // This call to M compiles fine because
        // Int32 implements IComparable AND IConvertible
        M(x);
        // This call to M causes a compiler error because
        // Guid implements IComparable but it does not implement IConvertible
        M(g);
    }

    // M's type parameter, T, is constrained to work only with types that
    // implement both the IComparable AND IConvertible interfaces
    private static Int32 M<T>(T t) where T : IComparable, IConvertible {
        ...
    }
}

type parameter constraint

private static List<TBase> ConvertIList<T, TBase>(IList<T> list) where T : TBase {
    List<TBase> baseList = new List<TBase>(list.Count);
    for (Int32 index = 0; index < list.Count; index++) {
        baseList.Add(list[index]);
    }
    return baseList;
}

Constructor Constraints

internal sealed class ConstructorConstraint<T> where T : new() {
    public static T Factory() {
        // Allowed because all value types implicitly
        // have a public, parameterless constructor and because
        // the constraint requires that any specified reference
        // type also have a public, parameterless constructor
        return new T();
    }
}

Back to posts


comments powered by Disqus