TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Cast Extension: System.Linq

This C# example demonstrates the Cast extension method from System.Linq.

Cast. The Cast method casts every element.

It is an extension method in the System.Linq namespace. It casts each element to the specified type. And the result is a collection of the desired type.

Example. First, this program introduces the A class and the B class. The two are connected—the B class derives from the A class. In the Main entry point, we create an array of B object instances.

Next: We use the Cast extension method with type parameter A. This means that each B object will be cast to its base class A.

C# program that uses Cast

using System;
using System.Linq;

class A
{
    public void Y()
    {
	Console.WriteLine("A.Y");
    }
}

class B : A
{
}

class Program
{
    static void Main()
    {
	B[] values = new B[3];
	values[0] = new B();
	values[1] = new B();
	values[2] = new B();

	// Cast all objects to a base type.
	var result = values.Cast<A>();
	foreach (A value in result)
	{
	    value.Y();
	}
    }
}

Output

A.Y
A.Y
A.Y

In this program, we have an IEnumerable collection of "A" instances. These are actually still "B" instances as well, but are now referenced through their base type. We call the Y() method to demonstrate that they are real "A" objects.

Numeric. The Cast extension method is less useful for casting numeric types. You cannot cast a double to an int without an exception. But implicit conversions are allowed. For example, you can cast an int to a uint.

Also: You can cast anything to the base class object. This is because everything is derived from object.

Numeric CastsObject Type

Summary. The Cast extension method is of limited utility in most programs. But if you need to cast a collection in a single statement, this is the best way to do it. Other LINQ articles on this site also show declarative programming techniques.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf