#1,051 – Implicit Reference Conversions

An implicit reference conversion is a conversion between reference types that is guaranteed to succeed and therefore does not require a cast operator.

Here are some examples:

            Dog dog = new Dog("Bowser");

            // From ref type to object
            object o1 = dog;

            // From ref type to dynamic
            dynamic dyn1 = dog;

            // From derived class to parent class
            Terrier terr = new Terrier("Jack");
            dog = terr;

            // From class to interface that class
            // implements
            IBark iBark = dog;

            // From a derived interface to
            // base interface
            IBarkWithStyle iBarkDerived = dog;
            iBark = iBarkDerived;

            // Covariant array conversion
            // Dog[] = Terrier[] ok because
            //    Dog = Terrier ok
            Terrier[] terriers = new Terrier[2];
            terriers[0] = new Terrier("Bobby");
            terriers[1] = new Terrier("Sydney");
            Dog[] dogs = terriers;

            // From array type to System.Array
            Array arr = terriers;

            // From array to IList<T>
            IList<Dog> dogList = terriers;

            // From any delegate-type to System.Delegate 
            // and the interfaces it implements
            MyStringHandlerDelegate del1 = HandleString;
            Delegate del2 = del1;

            // From null literal to any reference type
            Dog dog2 = null;

            // From any ref type to a ref type T if it has an 
            // implicit identity or reference conversion
            // to T0 and T0 has identity conversion to T.
            // E.g. can convert from Dog to object and
            //      from List to IEnumerable, so we can:
            List<Dog> somedogs = new List<Dog>();
            IEnumerable<object> genlist = somedogs;
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,051 – Implicit Reference Conversions

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: