Read the syntax
Distinguish filtering compatible objects from requiring every element to support a cast.
Where then removes the empty string using a normal string property.
What it is and why to use it
An older non-generic collection or a mixed event list may contain several runtime types. OfType<T> keeps non-null elements compatible with T, producing a typed sequence for further queries. Cast<T> instead requires each element to support the cast. Usually prefer a typed generic collection from the start; these operators help when an existing boundary supplies a broader collection.
How it works
Both operators use deferred execution: iteration reads the elements. OfType skips null and incompatible values. Cast performs reference and unboxing conversions, not parsing or arbitrary numeric conversions, and incompatible casts fail during enumeration. A boxed int therefore cannot be converted to long merely by Cast<long>. Null can be cast to a reference type, so Cast<string> does not guarantee non-null strings.
Common mistakes and limitations
Do not use OfType to silently discard invalid records when every record is required by the application. Do not expect Cast<int> to parse text such as "2". Put handling around enumeration when a query can fail there, and use Select with explicit parsing or conversion when that is the actual task.
Run the examples locally
These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.
Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.
C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.
Create and enter a project
dotnet new console -n CSharpExample --framework net10.0
cd CSharpExampleCSharpExample.csproj settings used for these examples
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<LangVersion>12.0</LangVersion>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>
</Project>Build and run after saving one example in Program.cs
dotnet build
dotnet run --no-buildContinue learning
Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.
Syntax
var matching = values.OfType<string>();
var required = values.Cast<string>();Examples
Select strings from a mixed collection
Filter before applying string-specific query logic.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
object?[] values = { "PHP", 2, null, "Ruby", "" };
var names = values.OfType<string>().Where(name => name.Length > 0);
Console.WriteLine(string.Join(", ", names));
- OfType<string> keeps the three string objects while excluding the integer and null.
- Where then removes the empty string using a normal string property.
- Enumeration by string.Join produces PHP and Ruby. Filtering is appropriate here because this operation deliberately asks only for nonempty strings.
- Expected output: PHP, Ruby
- Choose filtering or validation according to the data contract.
Observe a cast failure during enumeration
Show that creating a deferred query does not validate every element.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
object[] values = { 1, "2", 3 };
var numbers = values.Cast<int>();
Console.WriteLine("Query created");
try {
foreach (int number in numbers) Console.WriteLine(number);
} catch (InvalidCastException) {
Console.WriteLine("Incompatible element");
}
- Creating numbers stores the query without casting every element immediately.
- The first boxed int can be unboxed, but the string "2" cannot be cast to int.
- The catch surrounds iteration, where the failure occurs. The final value is not reached; use an explicit parsing policy when text numbers should be accepted.
- Expected output: Query created 1 Incompatible element
- Choose filtering or validation according to the data contract.
Best practices
- Choose filtering or validation according to the data contract.
- Distinguish a type cast from parsing and numeric conversion.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference