Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years' experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught "train-the-trainer" classes to get other MCTs up-to-speed on C# and .NET. Mark holds a Computer Science BSc. Hons. Degree.
Casting between types is subtly different from converting between types. Casting is between similar types, like between a 16-bit integer and a 32-bit integer, or between a superclass and one of its subclasses. Converting is between dissimilar types, such as between text and a number.
Implicit casting
In the previous example, you saw how an instance of a derived type can be stored in a variable of its base type (or its base's base type, and so on). When we do this, it is called implicit casting.
Explicit casting
Going the other way is an explicit cast, and you must use parentheses around the type you want to cast into as a prefix to do it:
In Program.cs, add a statement to assign the aliceInPerson variable to a new Employee variable, as shown in the following code:
Employee explicitAlice = aliceInPerson;
Your coding tool displays a red squiggle and a compile error, as shown in Figure 6.5:
...
The rest of the chapter is locked
Read this chapter and the full book FREE of cost - No Credit card required!
Plus access over 8,000 other expert tech books and videos just by signing up - No commitment!
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
50+ new titles added per month and exclusive early access to books as they are being written.
Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years' experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught "train-the-trainer" classes to get other MCTs up-to-speed on C# and .NET. Mark holds a Computer Science BSc. Hons. Degree.