#1,046 – Implicit vs. Explicit Conversions
March 5, 2014 3 Comments
A conversion occurs in C# when you convert an expression of one type to a different type. Often this occurs when you convert an instance of one type to an instance of another type.
Conversions can generally be broken down into two categories:
- Implicit
- Conversion can happen automatically
- Guaranteed to succeed
- No loss of data
- Explicit
- Requires a cast operator
- Required when either chance of failure or when there will be data loss
Below are some examples of both numeric and reference conversions, implicit and explicit.
int anInt = 12; // Implicit numeric conversion long aLong = anInt; // Explicit numeric conversion int newInt = (int)aLong; BorderCollie kirby = new BorderCollie("Kirby", 12); // Implicit reference conversion // - derived class to base class Dog d = kirby; // Explicit reference conversion // - base class to derived class, may fail // (This example will throw an InvalidCastException // because we're trying to convert a BorderCollie to a // Terrier). Terrier t = (Terrier)d;