Type Casting

Type Casting

Type Casting

Type casting in C# is the process of converting a value of one data type to another data type. There are two types of casting in C#:

  1. Implicit casting: This happens automatically when a value of a smaller data type is assigned to a variable of a larger data type. For example, assigning an int value to a long variable does not require an explicit cast, since the long data type is larger than int.
				
					int myInt = 10;
long myLong = myInt; // Implicit cast from int to long

				
			
  1. Explicit casting: This requires the use of the cast operator, which is the name of the destination type enclosed in parentheses. This is necessary when a value of a larger data type is assigned to a variable of a smaller data type, or when converting between different types that are not implicitly convertible.
				
					double myDouble = 3.141592653589793;
int myInt = (int)myDouble; // Explicit cast from double to int

				
			

Here, we’re casting a double value to an int value using an explicit cast. Note that the fractional part of the double value is truncated in the conversion.

It’s important to be careful when using explicit casting, as it can result in data loss or unexpected behavior if not done correctly. For example, casting a floating-point value to an integer type can result in rounding or truncation, depending on the type of casting used.

 

Join To Get Our Newsletter
Spread the love