Article ID: 304696 - View products that this article applies to.
This article was previously published under Q304696
When you compile your code, you receive the following compiler error message:
Cannot implicitly convert type <type> to <type>
Conversions must occur when you assign a variable of one type to a variable of a different type. When you make an assignment between variables of different types, the compiler must convert the type on the right side of the assignment operator to the type on the left side of the assignment operator. For example, consider the following the code:
Notice that the last statement is making an assignment, but the data types of the variables on the left and right sides of the assignment operator don't match. Before making the assignment, the compiler is implicitly converting the variable "lng", which is of type long, to type int. This is called implicit because the code does not explicitly tell the compiler to perform this conversion. The compiler is doing it automatically. The problem with this code is that this is considered a "narrowing" conversion, and implicit narrowing conversions are not allowed by the compiler. They are not allowed because a loss of data may result.
Narrowing vs. Widening ConversionsLet's take a moment to define what we mean by narrowing and widening conversions and why there is a potential loss of data.
Implicit narrowing conversions are not allowed, so to be able to compile this code you must explicitly convert the data type. Explicit conversions are done by using casting. Casting is the term used in C# to describe converting one data type to another. To get the code to compile, you would need to use the following syntax:
Notice that this precedes the right operand with a type name in parenthesis. This is so that the compiler knows that you want an explicit conversion to this type. This code sample is telling the compiler to explicitly convert the variable lng, which is of type long, to an int before making the assignment. We say that we are casting the variable lng to an int. Although this is allowed, you should note that with narrowing conversions there is a potential loss of data and they should be used with caution. Even though the code will compile, you may get unexpected results at run time.
In this article we have been working only with value types. When working with value types you work directly with the data stored in the variable. However, C# .NET has two types, value and reference. When working with reference types, you are working with a reference to a variable, not the actual data. Examples of reference types would be classes, interfaces, and arrays. You cannot implicitly or explicitly convert one reference type to another. Such types of conversions can be done by using the System.Convert class.
Implicit numeric conversions table
Explicit numeric conversions table