Cast Examples
This page was last reviewed on Nov 1, 2023.
Dot Net Perls
Casts. In C# code a set of complex rules resolves casts. In some cases data is lost and the cast cannot be reversed. In others an exception is provoked.
Conversions, specified as methods or operators, are often required. We can use ToArray and ToList to convert types. There is also a Cast() extension method.
Simple examples. We cast a double value to an int. This is an explicit numeric cast. Some casts may be implicit (not specified in the syntax).
Cast, Int
Tip With the is-operator we cast an object reference. Finally we cast that same reference with the as-operator.
So The StringBuilder is converted to an object and then back into a StringBuilder reference.
using System; using System.Text; // Numeric cast. int value = (int)1.5; Console.WriteLine(value); object val = new StringBuilder(); // Is cast. if (val is StringBuilder) { // As cast. StringBuilder builder = val as StringBuilder; Console.WriteLine(builder.Length == 0); }
1 True
Implicit, explicit. Implicit casts are not visible in the source text. The explicit (int) on the left side of a variable or expression casts to an int.
Here The integer cast succeeds. But we then try to cast to an invalid type.
Warning If you incorrectly use a cast expression, you will cause an InvalidCastException to be thrown.
using System; // Assign an int 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); }
400 System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String'. at Program.Main()
Convert. Conversions are possible for both simple values and complex data types. In this program, we use an extension from the System.Linq namespace to convert an array into a List.
using System; using System.Collections.Generic; using System.Linq; int[] array = { 1, 2, 3 }; List<int> list = array.ToList(); Console.WriteLine(array[0] == list[0]); Console.WriteLine(array.Length == list.Count);
True True
Strings, arrays, collections. With ToCharArray we convert a string into its equivalent char array. Custom methods, which often use Split, can parse more complex formats.
Convert Char, String
Convert Dictionary
Detail ToCharArray is provided on the string class. It returns the underlying buffer of a string as a char array.
String ToCharArray
using System; // 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);
t 4
Char. All chars have an underlying integer representation. A lowercase a, for example, is 97. We can implicitly cast a char to an int, as an int is larger.
However To cast from an int to a char, a cast is needed. This is a narrowing conversion where data loss is possible.
Info A char is only 2 bytes. But an int is 4 bytes—so larger numbers in an int cannot be safely turned into chars.
using System; for (char c = 'a'; c <= 'e'; c++) { // Cast the char to an int. int code = c; // Cast the int to a char. // ... An int is larger than a char. // ... So an explicit cast is needed. char original = (char)c; Console.WriteLine(c + "..." + code + "..." + original); }
a...97...a b...98...b c...99...c d...100...d e...101...e
Numeric promotion. C# uses numeric promotion when it needs to use smaller types as arguments to a method that receives a larger type. This occurs as part of an arithmetic expression.
So To get an int from an addition, you have to use 2 ints. But sometimes a number can be implicitly cast.
int, uint
Here We try to add a short and a ushort. The program compiles and executes correctly.
short, ushort
But In the addition expression, both variables are promoted to the int type. They can then fit into the binary operator for int addition.
using System; short a = 10; ushort b = 20; // Binary numeric promotion occurs here. // ... a and b become ints before they are added. int c = a + b; Console.WriteLine(c);
Cast extension. It is possible to call the Cast() function in System.Linq to cast variables. This will receive a certain type, and return values that have been cast.
Here The B class derives from the A class. We use the Cast extension—each B object will be cast to its base class A.
Return We have an IEnumerable of "A" instances. These are still "B" instances as well, but are now referenced through their base type.
And We call the Y() method to show that they are real "A" objects. The Y() method is only available on an "A" instance.
Tip You can cast anything to the base class object. This is because everything is derived from object.
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(); } } }
Operators. We can define conversion operators with method bodies. Implicit conversions require no special syntax. Explicit ones require a cast expression.
explicit, implicit
Summary. Casting relies on the type hierarchy. With the "is" and "as" operators we safely cast. For complex conversions, custom methods are needed.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 1, 2023 (simplify).
© 2007-2024 Sam Allen.