C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Operators: With the is-operator we cast an object reference. Finally we cast that same reference with the as-operator.
AsIsSo: The StringBuilder is converted to an object and then back into a StringBuilder reference.
C# program that uses casts
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: 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.
InvalidCastExceptionImplicit 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. Explicit casts are used when a value is reduced to fewer bytes.
C# program that uses cast expressions
using System;
class Program
{
static void Main()
{
// 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);
}
}
}
Output
400
System.InvalidCastException:
Unable to cast object of type 'System.Int32' to type 'System.String'.
at Program.Main()
Examples: These examples show how to convert types. The provided conversions are more complex than casts.
Here: In this program, we use an extension from the System.Linq namespace to convert an array into a List.
LINQC# program that converts array to List
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
ToCharArray: This method is provided on the string class. It returns the underlying buffer of a string as a char array.
ToCharArrayC# program that converts string, array
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
However: To cast from an int to a char, a cast is needed. This is a narrowing conversion where data loss is possible.
Sizes: A char is only 2 bytes. But an int is 4 bytes—so larger numbers in an int cannot be safely turned into chars.
C# program that casts char
using System;
class Program
{
static void Main()
{
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);
}
}
}
Output
a...97...a
b...98...b
c...99...c
d...100...d
e...101...e
So: To get an int from an addition, you have to use 2 ints. But sometimes a number can be implicitly cast.
Int, uintExample: We try to add a short and a ushort. The program compiles and executes correctly.
short, ushortBut: In the addition expression, both variables are promoted to the int type. They can then fit into the binary operator for int addition.
C# program that shows numeric promotion
using System;
class Program
{
static void Main()
{
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);
}
}
Output
30
Note: Type hierarchies are implemented with a matrix. In casts, this matrix determines if the cast succeeds. This is "transitive closure."
Quote: 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 (Compilers: Principles, Techniques and Tools).