Day 20 : Casting and Conversion in C#
Casting :
Casting means copying or converting a value from one data type to another data type. Casting is divided into two types :
1) Implicit casting :
- Implicit casting is done automatically by compiler when we pass smaller size type value to a larger size type.
- If we assign larger data type to smaller data type then it will won't work here.
- Smaller to larger data type : byte > short > int > long > float > double.
- Also before converting compiler checks the compatibility i.e only numeric data types are compatible with each other but no conversion is their between numeric to char or boolean.
- Also char and boolean are not compatible with each other.
- Their are many compilation error(missing cast) when types are not compatible with each other.
- Example :
2) Explicit casting :
- If we want to assign a value of larger data type to smaller data type we perform explicit casting.
- The explicit casting is done manually by user according to their need by placing data type in parenthesis in front of value.
- This is used for incompatible data types where automatic casting cannot be done.
- Example :
Conversion :
- The conversion means converting one type to another.
- Conversion is same as casting but here we use Convert.To() function for conversion.
- Some conversion methods are :
Thank You!!!
For more understanding watch below video :
Comments
Post a Comment