Sunday 21 April 2013

Introduce C# Generics

 Generics is a powerful feature of C#. Generics allow you to define type-safe classes without compromising type safety, performance, or productivity.

Lets think about example
Example
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

namespace GenericIntro
{
    class GenericIntro
    {
        private class ExampleClass { }
        static void Main()
        {
            System.Collections.ArrayList list = new System.Collections.ArrayList();
            // Add an integer to the list.
            list.Add(3);
            list.Add(2);
            list.Add(6);
            // Add a string to the list. This will compile, but may cause an error later.
            list.Add("It is raining in Redmond."); //illegal

            int t = 0;
            // This causes an InvalidCastException to be returned.
            foreach (int x in list)
            {
                t += x;
            }
        }
    }
}

With this example ,we can easily add to the list, but this convenience comes at a cost.
 Code above will pass compile,but will failed at run-time.

Generics Example


  // The .NET Framework 2.0 way to create a list
List list1 = new List();

// No boxing, no casting:
list1.Add(3);

// Compile-time error:
// list1.Add("It is raining in Redmond.");

Conclusion: With Generics you can produce type safety code + reusable.

Remind: This feature is not often useful when you'r coding.You rarely need to create your generic types because .net Framework contains many useful classes already.

Reference from MSDN.
Example code from MSDN.

No comments:

Post a Comment