C# Cast Examples

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

Cast to int (int)

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 in the execution engine. The C# language also allows a variety of syntax forms.

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

Int cast

First, this short program introduces casts in the C# programming language. You can see how a double value is casted to an integer; how an object reference is casted with the 'is' operator; and how that same reference is casted with the 'as' operator.

Program that uses cast expressions [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

Implicit/explicit example

Next, this example shows implicit and explicit casts. You can use the explicit (int) on the left side of a variable or expression that is evaluated to a value 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 a InvalidCastException to be thrown.

Implicit casts: Intended never to provoke an exception.

Explicit casts: Allowed to provoke an exception.

Program that uses cast expressions [C#]

using System;

class Program
{
    static void Main()
    {
	// Assign an integer and then cast it to an object implictly.
	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 casts

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. Additionally, the as cast will result in exception-neutral code, which is also faster code. Please see the separate articles on the as and is cast operators.

as is

Overview: These C# examples focus on casting variables. The as and is casts are shown.

Numeric casts

Int keyword

The C# language also supports casting numbers in many different ways. We talk about how you can cast numeric values, exploring the intermediate language as well. Next, we show what happens when you cast fractional values to ints, which is a useful technique for rounding numbers.

Numeric Casts Cast to Int

Type hierarchies

Programming tip

Type hierarchies are 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, and this represents the mathematical principle of transitive closure. When casting types, the adjacency matrix can be used to determine if the cast succeeds, without incurring a large delay.

Dragon Book: Compilers Compiler Explanation

Summary

The C# programming language

We explored cast expressions in the C# language, demonstrating the explicit cast and implicit cast. Further, we demonstrated how the explicit cast expression can provoke a runtime exception. Finally, we touched on the concept of the type hierarchy and its theoretical implementation, as well as various alternative casts available to you.

Dot Net Perls