Can we restrict the type to a delegate?

We can restrict a type to a class or structure. Can we restrict the type to a delegate?

+4
source share
2 answers

A Delegate is a class, and you can usually specify a non-printable class as a constraint. However, the language specification specifically excludes System.Delegate as a valid limitation in section 10.1.5.

A class type constraint must satisfy the following rules:

  • The type must be a class type.
  • Type must not be closed.
  • The type must not be one of the following types: System.Array, System.Delegate, System.Enum, or System.ValueType.
  • The type should not be an object. Since all types are descended from an object, such a restriction will have no effect if it was allowed.
  • At most one restriction for a given type parameter can be a class type.
+8
source

As already noted, the C # specification does not admit a general Delegate restriction. Nor are subclasses of Delegate accepted by the compiler as a general limitation. The best you can do is check and throw an exception. I will show this with a method, but if it is a general class, the constructor will be a great place to check.

 public void Foo<T>(T x) { if (x == null) throw new ArgumentNullException("x"); Delegate d = x as Delegate; if (d == null) throw new ArgumentException("Argument must be of Delegate type.", "x"); // Use d here. } 
+2
source

All Articles