#1,046 – Implicit vs. Explicit Conversions

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;

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #1,046 – Implicit vs. Explicit Conversions

  1. Pingback: Dew Drop – March 5, 2014 (#1736) | Morning Dew

  2. Pingback: #1,052 – Boxing Is a Kind of Implicit Conversion | 2,000 Things You Should Know About C#

  3. Pingback: #1,065 – Cases When Array Covariance Doesn’t Work | 2,000 Things You Should Know About C#

Leave a comment