C# is statically-typed at compile time, after a variable is declared, it cannot be declared again or assigned a value of another type unless that type is implicitly convertible to the variable's type.
For example, the string
cannot be implicitly converted to int
. Therefore, after you declare i
as an int
, you cannot assign the string "Hello" to it.
Implicit Conversion
No special syntax is required because the conversion is type safe and no data will be lost.
Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
Explicit Conversion
Explicit conversions require the cast operator ()
. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.