Generics Type Identity

 

1. How to define a generic type to improve its readability?

2. How to avoid losing type identity?

To improve generic type readability we can use the using directive. We should avoid defining a new type by deriving from the generic base type, trying to reach readability, because it leads to losing type identity and equivalency.

 

Example:

    using StringList = List<string>;

 

    public class OtherStringList : List<string> {}

 

    class Program

    {

        static void Main(string[] args)

        {

            //The result is false because OtherStringList is a derived type from List<String>

            Trace.WriteLine(typeof(OtherStringList) == typeof(List<String>));

 

            TryToPassDerivedParameter(new OtherStringList());

 

            //Returns compile-time error: cannot convert from ‘System.Collections.Generic.List<string>’

            //to ‘GenericsIdentity.OtherStringList’

            TryToPassBaseParameter(new List<string>());

 

            //Returns true because the StringList is just an another name of the List<String> class.

            Trace.WriteLine(typeof(StringList) == typeof(List<String>));

            Console.ReadKey();

        }

 

        static void TryToPassDerivedParameter(List<string> strList)

        {

 

        }       

 

        static void TryToPassBaseParameter(OtherStringList oStrList)

        {

 

        }

    }

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 )

Connecting to %s