1.10. Implicit Type Conversions and Explicit Casting

C# supports implicit type conversions. For example, we try to assign the value of some variable y to another variable x, as shown here:

x = y;

The two variables were originally declared to be of different types; then C# will attempt to perform the assignment, automatically converting the type of the value of y to the type of x, but only if precision won't be lost in doing so. (C# differs from C and C++ in this regard because the latter two perform automatic type conversions even if precision is lost.) This is best understood by looking at an example:

int x; double y; y = 2.7; x = y; // Trying to assign a double value to an int variable; this line // will compile in C and C++, but not in C#. ...

Get Beginning C# 2008 Objects: From Concept to Code now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.