C# Casts

Array Class Collections File Keyword String .NET ASP.NET Cast Compression Data Delegate Directive Enum Exception If Interface LINQ Loop Method Number Process Property Regex Sort StringBuilder Struct Switch Time Windows WPF

Cast: int, byte

Casting variables is not simple. A complicated set of rules resolves casts. In some cases data is lost and the cast cannot be reversed. In others an exception is provoked. Complex conversions are often required.

Example

First, this program introduces casts. It casts a double value to an integer. Then it casts an object reference with the is-operator. And finally it casts that same reference with the as-operator.

So:The StringBuilder is converted to an object and then back into a StringBuilder reference.

Based on:

.NET 4.5

Program that uses casts: C#

using System;
using System.Text;

class Program
{
    static void Main()
    {
	int value = (int)1.5; // Cast 1.
	Console.WriteLine(value);

	object val = new StringBuilder();
	if (val is StringBuilder) // Cast 2.
	{
	    StringBuilder builder = val as StringBuilder; // Cast 3.
	    Console.WriteLine(builder.Length == 0);
	}
    }
}

Output

1
True

Example 2

Skew transform on rectangles

Next, this example shows implicit and explicit casts. Implicit casts are not visible in the source text. We use the explicit (int) on the left side of a variable or expression to cast to an int.

In the example, the integer cast succeeds. However, we then try to cast to an invalid type. If you incorrectly use a cast expression, you will cause an InvalidCastException to be thrown.

InvalidCastExceptionNote

Implicit casts:Intended never to provoke an exception. These are used when a value is expanded to more bytes.

Explicit casts:Allowed to provoke an exception.
These are used when a value is reduced to fewer bytes.

Program that uses cast expressions: C#

using System;

class Program
{
    static void Main()
    {
	// Assign an integer and then cast it to an object implicitly.
	int value1 = 400;
	object value2 = value1;

	// Explicitly cast to an integer again.
	int value3 = (int)value2;
	Console.WriteLine(value3);

	// Try to cast it to a string.
	try
	{
	    string value4 = (string)value2;
	}
	catch (Exception ex)
	{
	    Console.WriteLine(ex);
	}
    }
}

Output

400
System.InvalidCastException:
   Unable to cast object of type 'System.Int32' to type 'System.String'.
   at Program.Main()

As, is

As keyword

In the C# language, we typically prefer the as-cast and is-cast operators for reference types. The as-cast will allow you to actually store the result of the cast in a local variable, in the same expression.

Also:The as-cast will result in exception-neutral code, which is also faster code.

asis

Numeric casts

Cast to int

Many casts apply to number types. The C# language supports casting numbers in many different ways. We explore how you can cast numeric values, exploring the intermediate language as well.

Next:We show what happens when you cast fractional values to ints. This is a useful technique for rounding numbers.

Numeric CastsCast to Int

Type hierarchy

Question

Compilers have advanced support for casting. A type hierarchy is used to specify behavior through structure of source text. This means you can specify differences in methods called through the derivation chain.

Typically, type hierarchies are efficiently implemented with a matrix data structure. This represents the mathematical principle of transitive closure. When casting types, the adjacency matrix determines if the cast succeeds.

Compiler

Convert

Convert or change

A List is not an array. This is not a problem unless you need an array. Conversions are possible for both simple values and complex data types. These conversions are sometimes complicated and involved.

Note:These C# examples show how to convert types. These conversions are more complex than casts.

Here:In this example program, we use the System.Linq namespace to convert an array into a List.

Program that converts array to List: C#

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	int[] array = { 1, 2, 3 };
	List<int> list = array.ToList();
	Console.WriteLine(array[0] == list[0]);
	Console.WriteLine(array.Length == list.Count);
    }
}

Output

True
True

List collections. A common task is converting to and from the List type. These articles demonstrate how you can reliably do this. We provide examples for conversions in both directions.

Dictionary to ListList to DataTableList to StringArray type

Convert arrays. Some of the more complicated conversion methods involve an array type. These articles demonstrate how you can convert various types, such as ArrayList, string, and List, into arrays and back again.

ArrayList to ArrayArrayList to ListChar Array to StringList to ArrayString Array to StringString to Byte ArrayCopyright

The BitConverter type in the C# language provides a way to convert byte arrays into integral value types, and the opposite. This tutorial helps you discover and use the BitConverter type.

BitConverter

Note:For some types and collections, custom conversion methods, even complex ones, are necessary.

However:For simpler value types, using a casting expression is sufficient and will be much faster as well.

Numeric

Value

Most numeric conversions involve a multiplication or division expression. They can be tested using the Google search engine. These examples reliably convert different units of measurement.

Bytes, Megabytes, GigabytesCelsius to FahrenheitDays to MonthsFeet to InchesMiles to KilometersMilliseconds to SecondsNanoseconds to Milliseconds

Bools:You cannot convert bools and ints directly. Instead, you must use expressions to convert them as needed.

Bool to IntInt to Bool

Values:Value types, such as the TimeSpan struct, can be converted into long values.

Convert TimeSpan to Long

Convert:The Convert type provides ways to convert values to Int32 with Convert.ToInt32.

Convert.ToInt32

Strings

String type

Strings are often converted to other types. These tutorials provide examples for string-specific conversions. There are other string conversions available in this category as well.

Char to StringDictionary to StringString to Int

Here:We convert a string into its equivalent char array. We use the built-in method ToCharArray for convenience.

ToCharArray
Program that converts string, array: C#

using System;

class Program
{
    static void Main()
    {
	// A string value.
	string value = "test";

	// Convert the string into an array.
	char[] array = value.ToCharArray();

	// Display parts of the array.
	Console.WriteLine(array[0]);
	Console.WriteLine(array.Length);
    }
}

Output

t
4

Operators

Operator keyword

You can define conversion operators. These work at the level of the language to convert one type to another. Implicit conversions require no special syntax. Explicit conversions require a cast expression.

implicitexplicit

Research

File: text page

Compiler textbooks have information on casting. We learn that an implicit conversion is one done automatically by the compiler. This kind of cast is also called a "coercion." The C# compiler limits coercions to larger types.

Conversion from one type to another is said to be implicit if it is done automatically by the compiler. Implicit type conversions, also called coercions, are limited in many languages to widening conversions. Aho et al., p. 388

Summary

C# programming language

Cast expressions abound in the C# language. We demonstrated explicit and implicit casts. An explicit cast expression can provoke a runtime exception. An implicit one does not. Casting relies on the type hierarchy.

Finally:We probed the limits of casting.
For complex conversions, custom methods are needed.

C#