Generic interfaces

Advantages of using generic interfaces.

  1. Compile – time safety.
  2. Much less boxing
  3. Backward compatibility with non-generic interfaces.
  4. Availability to implement generic interface several times, as long as different type parameters are used.

Example 1.1:

    class CompileTimeSafetyTest : IComparable

    {

        int x = 0;

        public int CompareTo(object param)

        {

            return x.CompareTo(param);

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            CompileTimeSafetyTest ctsTest = new CompileTimeSafetyTest();

            ctsTest.CompareTo(2);

            //Run-time error. Object must be of an Int32 type.

            ctsTest.CompareTo("2");

        }

    }

Example 1.2:

    class CompileTimeSafetyTest : IComparable<int>

    {

        int x = 0;

        public int CompareTo(int param)

        {

            return x.CompareTo(param);

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            CompileTimeSafetyTest ctsTest = new CompileTimeSafetyTest();

            ctsTest.CompareTo(2);

            //Compile-time error. Cannot convert from ‘string’ to ‘int’.

            ctsTest.CompareTo("2");

        }

    }

1.                          As we can see from the examples above generic interface provides compile type safety.

2.                          The second benefit of generic interfaces is much less boxing will occur when we working with value types.

Example 2:

class CompileTimeSafetyTest : IComparable, IComparable<int>, IComparable<string>

{

        int x = 0;

        string s = "test";

               

        public int CompareTo(object param)

        {

             throw new ArgumentException("Can’t compare your type");        

        }

 

        public int CompareTo(int param)

        {

            IComparable<int> compInt = x;

            return compInt.CompareTo(param);

        }

 

        public int CompareTo(string param)

        {

            IComparable<string> compString = s;

            return compString.CompareTo(param);

        }

}

 

3.                          For the backward compatibility we must implement non-generic version of an interface as well.

4.                          The forth benefit is that we can implement the same generic interface multiple times as long as different type parameters are used.

 

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