views:

57

answers:

3

Can anyone explain the (of Out T) component to this interface? I'm familar enough with how interfaces work. I also understand that T refers to a type... Whats going on with the Out portion.

Public Interface IPageOfItems(Of  Out T)
Inherits IEnumerable(Of T)
        Property PageNumber() As Integer
        Property PageSize() As Integer
        Property TotalItemCount() As Integer
        ReadOnly Property TotalPageCount() As Integer
        ReadOnly Property StartPosition() As Integer
        ReadOnly Property EndPosition() As Integer
    End Interface
A: 

This is to indicate the interface is covariant in generic parameter T. Check Generic Variance heading in this article that explains new features in VB.NET 2010 (.NET Fx 4.0).

In short covariance will allow to substitute smaller type (such as subclass) instead of larger type. For example, if Tiger is inherited from Animal then we can use IEnumerable(Of Tiger) in place of IEnumerable (Of Animal). Eric Lippert has explained variance (in context C#) very well in series of blog posts.

VinayC
A: 

This is new .NET 4 feature that allows you to specify variance with generic arguments. Pretty much everything you need to know:

http://msdn.microsoft.com/en-us/library/dd799517.aspx

Ian Henry
+1  A: 

.NET 4.0 introduced covariance and contravariance of generic types. Here's what this means.

Covariance

The Out keyword here indicates that the type is covariant. A covariant type T(Of D) can be cast to a type T(Of B) where D derives from B. This is possible when the type T(Of D) only ever uses D values as output (hence the word Out).

For example, the IEnumerable(Of Out T) interface is covariant because none of its methods accepts any parameters of type T. Therefore, an IEnumerable(Of String) can be cast as an IEnumerable(Of Object) -- if it provides enumerable access to strings, then it provides enumerable access to objects (since strings are objects).

Contravariance

Conversely, the In keyword may be applied to a type that is eligible for contravariance. A contravariant type T(Of B) can be cast to a type T(Of D) where D derives from B. This is possible when the type T(Of B) only uses B values as input (hence the word In). In other words, contravariance is the exact opposite of covariance.

A good example of a contravariant type would be the IComparer(Of In T) interface. This interface provides no methods that return T values; therefore an IComparer(Of Object) could be cast as an IComparer(Of String) -- after all, if it can compare objects, it can compare strings.

Dan Tao