An Introduction to Type Casting in C#

C# Programming Guide


C# is a statically-typed language, which implies that developers cannot assign the value of one variable or an object to another unless they are compatible types. Additionally, programmers cannot assign incompatible type values (i.e., values that have a type that is not the same as the type of the variable or object).

This programming tutorial talks about type casting, types of type casting, and how to program type casting in C#.

Before we begin learning about type casting, we have a list of the Best Online Courses to Learn C# that you may want to bookmark if you prefer to learn in an online course setting.

What is Type Casting in C#?

Type casting is a built-in feature of the C# programming language that enables developers to convert a variable or an object of one type to another. In other words, it is used to assign the values of one type to another. There are two terms you will often come across when discussing typecasting in C#: boxing and unboxing.

While boxing refers to converting a value type to a reference type (i.e., object), unboxing refers to the transformation of a reference type to a value type. A value type is considered to be boxed when transformed into an object type.

Boxing is an implicit conversion because it does not require a cast operator. However, unboxing is an explicit conversion because it requires you to specify a cast operator.

Implicit and Explicit Type Casting in C#

In implicit type casting, a type is converted to another without using a cast operator explicitly. This is used when the compiler determines that transformation of a variable of one data type to another is safe.

Boxing refers to the transformation of a value type variable into an instance of a reference type. Boxing is an implicit conversion since it doesn’t require a cast operator. Unboxing involves extracting value types from object types.

Because unboxing requires a cast operator, it is an explicit conversion. A value type is said to be boxed when it is converted to an object type. Boxing refers to the fact that the value type is enclosed within an object. Since boxing does not require a cast operator, it is an implicit conversion.

When a variable of a particular value type is assigned to a reference type variable, the value type variable is said to have been boxed. For example, in the following code example, the int variable i is implicitly converted to an object reference:

int i = 10;
object o = i; // The variable i is boxed 

Unboxing is defined as the process of extracting a value type from an object type. The unboxing process requires a cast operation, so it is an explicit conversion. For example, in the following C# code example, the object reference o is explicitly converted to an int:

int i = 5;
object obj = i; // Boxes i
int j = (int)obj; // Unboxes obj

When you convert a data type to another data type that can hold a larger range of values, it is called widening conversion. For example, if you convert an integer variable to a long data type it would be a widening conversion since the long data type can contain a wider range of values. Widening conversion never loses information; they can only add information.

When you convert a data type to another data type that can hold a smaller range of values, it is called narrowing conversion. For instance, the conversion of a long to an int is a narrowing conversion because an int can store fewer values.

Narrowing conversions can lose information: they can never add information. To allow narrowing conversions, you must explicitly cast the data type using the (type) syntax. You will write (int)value to transform a long variable to an int.

Read: The Top Task Management Software for Developers

Upcasting and Downcasting in C#

The methods of upcasting and downcasting are related to the concept of inheritance. While the upcasting refers to casting an instance of a derived class to an instance of its base class, downcasting refers to casting an instance of the base class to instances of any of its derived classes.

For example, assume there are two classes, namely, Base and Derived. The following code examples demonstrates upcasting in C#:

Base b = new Derived(); // Upcasting

And, the following code snippet illustrates how programmers can implement downcasting in C#:

Derived d = (Derived)b; // Downcasting

Benefits and Downsides of Typecasting in C#

As mentioned, in C#, there are two types of typecasting: implicit and explicit. There are benefits and downsides to both implicit and explicit typecasting. Implicit typecasting is when the compiler automatically converts one data type into another and is usually done with smaller data types (e.g., int to float).

With implicit typecasting, the programmer does not have to worry about explicitly converting data types, which can save time and effort. However, implicit typecasting can sometimes lead to unexpected results since the compiler may not always make the conversion the way the programmer intends.

Explicit typecasting is when the developer casts a data type into another (e.g., float to int). With explicit typecasting, the developer has more control over how data types are converted from one type to another.

However, writing explicit typecasts can be more tedious every time a conversion is needed. In general, it is best to use implicit typecasting unless there’s a specific reason to use explicit typecasting. That way, you can let the compiler handle most of the conversions for you while still being able to control transformations when necessary.

Read: Top 10 Security Testing Tools for Developers

User-defined Conversions

User-defined conversions are a powerful and convenient mechanism for converting between types that you have created. If this conversion can occur without the need of a conversion operator, it is an implicit cast. On the contrary, if you need a conversion to transform an object into another, it is an explicit cast. By defining a conversion operator, you can enable conversions both from your type to another type, and from another type to your type.

Conversion operators have associated overloaded methods that implement the conversion between two types. They are defined as static members of the class or struct that is being converted, and they take one parameter of the type being converted to. The following example defines a user-defined conversion from an int to a user defined type named MyCustomClass:

    public class MyCustomClass
        static int x;
        public static implicit operator MyCustomClass(int i)
            x = i;
            return MyCustomClass.x;

The explicit keyword can be used instead of implicit to make a conversion operator that can only be used explicitly (i.e., with a cast). It should be noted that User-defined conversions are available in C# 3.0 and later versions.

Final Thoughts on Type Casting in C#

Type casting is one of the most widely used features of the C# programming language. Implicit type casting can occur if the types are compatible. For incompatible types, you must use explicit type casting to assign values from one type variable to another.

Read more C# programming tutorials and software development tips.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read