C# TutorialLesson 9Free preview
C# Type Casting
This lesson is part of C# · All levels
Summary
Type casting is the conversion of values from one type to another type, for example from int to double. Automatic conversion (implicit) occurs when the target type is broader, whereas explicit conversion uses the type parentheses in front of the value. In addition, there are converts and parse methods, with the risk of errors when the source data is not matched.
Key points
- The implicit conversion runs automatically from the narrower type to the wider type, for example int to double.
- The explicit conversion uses casting like (double) and can cut data when the source type is larger, for example double to int.
- Convert classes such as Convert.ToInt32 facilitate conversion from strings or other types.
- Converting the string to a number is best done using Parse or TryParse to handle errors.
- Turning objects into concrete types is called unboxing and can fail if the type doesn't fit.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.