Several examples were presented in the previous chapter of how the many simple types found in C# impose a complicated life for the compiler. We saw how the C# compiler attempts to handle the often tricky situations of assignment statements by performing implicit conversions, and how the programmer can interfere by using explicit conversions in the form of type casts.
In this section, we will look at how operators affect the type of the value returned from a numerical expression. This will enable you to determine the type of expressions, such as
which mixes together two types. Because any expression only has one value with one type, a choice must be made.
The rules used to determine the type of an expression based on its elements and its relevant context are called type inference rules.
For the uninitiated, even the simple unary minus operator can produce values with unexpected types, just as in the following expression where height is of type byte.
Surprisingly, the value returned from -height is of type int.
Automatic conversions are often performed in numerical expressions written in C#. A lack of understanding of these conversions and their accompanying results will often leave you mystified and can cause you to waste time on seemingly unfixable errors errors that could have been removed with simple remedies.
Note
Automatic type conversions are performed by the C# compiler when
We have already dealt with the first two points in Chapter 6 and will discuss the last two aspects in the following section. |
We will first look at the very simple expressions formed when applying one of the unary plus or minus operators on an operand.
Internally, C# only supports the use of the unary plus and minus operators on numbers of the int, uint, long, ulong, float, double, and decimal types; leaving out byte, sbyte, short, and ushort.
You can still use the unary operators on those latter integer types. However, in these cases, it forces C# to convert to the nearest type it can deal with, which is int. Thus, whenever you apply either the unary plus or the unary minus operator to a value of type byte, sbyte, short, or ushort, the operation will return a value of type int.
For example, the following code snippet:
will cause the C# compiler to report the following error:
Cannot implicitly convert type 'int' to 'short'.
To prevent this error, you will need a cast explicitly converting -height to type short as in the following:
When a conversion is made from one type to another type with a broader range and/or higher precision, it is termed a numeric promotion.
A value of type short converted to a value of type int is an example of a numeric promotion.
Unary Numeric Promotions
Whenever the unary plus (+) or the unary minus operator (-) are applied to an operand of type sbyte, byte, short, ushort, or char, the numerical expression will have the type int. If the unary minus operator is applied to an operand of type uint, the expression will be of type long. |