kdbanman
kdbanman

Reputation: 10557

What does it mean to constrain a type parameter with `new()`?

Here is a class signature from the popular EmguCV package. It's the Image class - not all of it is important:

/// <summary>
/// An Image is a wrapper to IplImage of OpenCV. 
/// </summary>
/// <typeparam name="TColor">Color type of this image (either Gray, Bgr, Bgra, Hsv, Hls, Lab, Luv, Xyz, Ycc, Rgb or Rbga)</typeparam>
/// <typeparam name="TDepth">Depth of this image (either Byte, SByte, Single, double, UInt16, Int16 or Int32)</typeparam>
public partial class Image<TColor, TDepth>
  : CvArray<TDepth>, IImage, IEquatable<Image<TColor, TDepth>>
  where TColor : struct, IColor
  where TDepth : new()

Specifically, note

  ...
  where TDepth : new()  // <-- either Byte, SByte, Single, double, UInt16, Int16 or Int32

How does new() constrain the type parameter TDepth to the .NET integral types?

Upvotes: 2

Views: 65

Answers (1)

David L
David L

Reputation: 33815

It doesn't. All new() guarantees is that the generic type with the constraint (in this case TDepth) MUST provide a parameterless constructor and that it is not abstract, per the documentation.

Upvotes: 6

Related Questions