Enumerable::Cast<TResult> Method (IEnumerable^)

 
System_CAPS_noteNote

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

Casts the elements of an IEnumerable to the specified type.

Namespace:   System.Linq
Assembly:  System.Core (in System.Core.dll)

public:
generic<typename TResult>
[ExtensionAttribute]
static IEnumerable<TResult>^ Cast(
	IEnumerable^ source
)

Parameters

source
Type: System.Collections::IEnumerable^

The IEnumerable that contains the elements to be cast to type TResult.

Return Value

Type: System.Collections.Generic::IEnumerable<TResult>^

An IEnumerable<T> that contains each element of the source sequence cast to the specified type.

Type Parameters

TResult

The type to cast the elements of source to.

Exception Condition
ArgumentNullException

source is null.

InvalidCastException

An element in the sequence cannot be cast to type TResult.

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

The Cast<TResult>(IEnumerable^) method enables the standard query operators to be invoked on non-generic collections by supplying the necessary type information. For example, ArrayList does not implement IEnumerable<T>, but by calling Cast<TResult>(IEnumerable^) on the ArrayList object, the standard query operators can then be used to query the sequence.

If an element cannot be cast to type TResult, this method will throw an exception. To obtain only those elements that can be cast to type TResult, use the OfType<TResult> method instead of Cast<TResult>(IEnumerable^).

In a query expression, an explicitly typed iteration variable translates to an invocation of Cast<TResult>(IEnumerable^). This example shows the syntax for an explicitly typed range variable.

No code example is currently available or this language may not be supported.

The following code example demonstrates how to use Cast<TResult>(IEnumerable^) to enable the use of the standard query operators on an ArrayList.

No code example is currently available or this language may not be supported.

Universal Windows Platform
Available since 8
.NET Framework
Available since 3.5
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
Show: