Thursday, August 21, 2008

Generics

In framework 2 Microsoft introduced support for generic types. Generic can take on any type; it might sound familiar to you; objects can do exactly the same. Generics are to replace objects when possible, since they firstly improve the performance by eliminating the need to boxing and unboxing, secondly decrease the number of run-time errors caused by incorrect casting.

Here is an example of incorrect casting:

object MyObj=new object();

MyObj="Not an integer";

int MyNumber=(int)MyObj;//CAUSES RUN-TIME ERROR

The above mistake won't be caught by the compiler and as a result will generate a run-time error.

The class definition does not provide the exact variable types and when the class is used, the exact types are passed to the class.

The following is the definition of a class that uses generic concept:

class MyGenericClass<MyGenericTypeOne,MyGenericTypeTwo>
    {
        private MyGenericTypeOne MyFieldOne;
        private MyGenericTypeTwo MyFieldTwo;
        public MyGenericTypeOne MyPropertyOne
        {
            get
            {
                return MyFieldOne;
            }
            set
            {
                MyFieldOne = value;
            }
        }

        public MyGenericTypeTwo MyPropertyTwo
        {
            get
            {
                return MyFieldTwo;
            }
            set
            {
                MyFieldTwo = value;
            }
        }
    }

 

MyGenericTypeOne and MyGenericTypeTwo are two generic types that the above class uses.

The following code consumes the above class:

 

MyGenericClass<string,int> NewInstanceOne=new MyGenericClass<string,int>();
NewInstanceOne.MyPropertyOne = "Some text";
NewInstanceOne.MyPropertyTwo = 10;

MyGenericClass<double, Uri> NewInstanceTwo = new MyGenericClass<double, Uri>();
NewInstanceTwo.MyPropertyOne = 2.2;
NewInstanceTwo.MyPropertyTwo = new Uri("http://mycomputerknowhow.blogspot.com");

 

As you can see, when, in this case, instantiating the class, the exact type of the generic type is specified.

If MyGenericClass were a static class including all static members, you would pass the exact types as follows:

MyGenericClass<string, int>.MyPropertyOne = "string";
MyGenericClass<int, int>.MyPropertyOne = 10;

Debug.WriteLine(MyGenericClass<int, int>.MyPropertyOne);
Debug.WriteLine(MyGenericClass<string, int>.MyPropertyOne);

In the above code, classes MyGenericClass<string, int> and MyGenericClass<int, int> are in fact completely isolated from each other and can hold different values.

Though we have one class definition, since the actual types are different, MyGenericClass<string, int> and MyGenericClass<int, int> are two separate classes with different types.

No comments: