TheDeveloperBlog.com

Home | Contact Us

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

C# Cast Examples and Conversions

These C# examples focus on casting variables. They cover complex conversions between types.

Casts. Casting variables is complex.

A set of 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. Lists and arrays are similar, but not the same. To convert, we use ToList and ToArray.

A first program. We cast a double value to an int. This is an explicit numeric cast. Some casts may be implicit (not specified in the syntax).

Is, as: 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.

Based on:

.NET 4.5

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

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.

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.

InvalidCastException

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. 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()

As-operator. This cast allow us to store the result of the cast in a local variable, in a single expression. I recommend "as" for all reference types.

as

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

Is-operator. This is the same as the as-operator but it returns true or false, not a variable reference. If we use "is," we may end up casting too many times.

is

Numeric casts. Many casts apply to number types. We cast numeric values. We explore the intermediate language's casting instructions.

Numeric Casts

Cast to int. We can cast fractional values, like doubles, to ints. This is a useful technique for rounding numbers. It can be used as an optimization.

Cast, Int

Type hierarchy. This is used to specify behavior based on the structure of a program. We specify differences in methods called through the derivation chain.

Note: Type hierarchies are implemented with a matrix. In casts, this matrix determines if the cast succeeds. This is "transitive closure."

Convert. A List is not an array. This is no problem unless we need an array. Conversions are possible for both simple values and complex data types.

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.

LINQ

C# 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

List. This is a generic collection. Often we must convert Lists to Dictionaries, strings, and DataTables. And the opposite conversions too are needed.

List to DictionaryList to DataTableList to String

Arrays. Some of the more complicated conversion methods involve an array type. We 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 Array

BitConverter. This class converts byte arrays into integral value types, and the opposite. This tutorial uses and tests BitConverter.

BitConverter

Methods versus casts. For many classes, custom conversion methods, even complex ones, are needed. But for simpler value types, using a casting expression is sufficient. It is also faster.

Numeric. Most numeric conversions involve a multiplication or division expression. I developed (and tested) some reusable unit conversion methods.

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

Bools. We cannot directly convert bools and ints. The .NET Framework disallows this. Instead we must use expressions to convert them as needed.

Bool to IntInt to Bool

TimeSpan. Our programs use many built-in structs like TimeSpan. We can convert TimeSpan into a long value. This may be easier to persist to disk.

TimeSpan to long

Strings. Often our programs have string data that represents numbers or times. With int.Parse and TryParse, we can parse that data into an int.

String to int

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.

Char to StringDictionary to String

ToCharArray: This method is provided on the string class. It returns the underlying buffer of a string as a char array.

ToCharArray

C# 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

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.

Char

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

Operators. We can define conversion operators with method bodies. Implicit conversions require no special syntax. Explicit ones require a cast expression.

implicitexplicit

In compiler textbooks, we learn that an implicit conversion is one done automatically. This kind of cast is called a "coercion." The C# compiler limits coercions to lossless operations.

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

Cast expressions abound. We demonstrated explicit and implicit casts. An explicit cast expression can provoke a runtime exception. An implicit one does not.

To sum up: casting relies on the type hierarchy. With the "is" and "as" operators we safely cast. For complex conversions, custom methods are needed.


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