CLR Support for Generics:


 


CLR supports and recognize generics. The important concept behind this is for instance, if you define a generic type MyList<T>, only one definition of that type is present in MSIL. When the program executes, different classes are dynamically created, one for each type for the parameterized type. If you use MyList<int> and MyList<double>, then two classes are created on the fly when your program executes.


 


Generic Class in .Net 2.0


 


Demonstrate: Example of Generic Class


 


//******************************MyList.cs************************


#region Using directives


using System;


using System.Collections.Generic;


using System.Text;


#endregion


 


namespace CLRSupportExample


{


public class MyList<T>


{


private static int objCount = 0;


  public MyList () {


    objCount++;


  }


public int Count {


  get


  { return objCount;}


  }


}


}


 


//****************************Program.cs*************************


 


#region Using directives


using System;


using System.Collections.Generic;


using System.Text;


#endregion


 


namespace CLRSupportExample


{


class SampleClass {}


class Program


{


static void Main (string[] args)


{


    MyList<int> myIntList = new MyList<int>();


    MyList<int> myIntList2 = new MyList<int>();


    MyList<double> myDoubleList= new MyList<double>();


    MyList<SampleClass> mySampleList= new MyList<SampleClass>();


 


  Console.WriteLine(myIntList.Count);


  Console.WriteLine(myIntList2.Count);


  Console.WriteLine(myDoubleList.Count);


  Console.WriteLine(mySampleList.Count);


  Console.WriteLine(new


  MyList<SampleClass>().Count);


  Console.ReadLine();


    }


}


}


 


Here we have generic class named MyList. Within the MyList class, I have a static field, objCount. I am incrementing this within the constructor so I can find out how many objects of that type is created by the user of my class. The Count property returns the number of instances of the same type as the instance on which it is called.


In the Main() method, I am creating two instances of MyList<int>, one instance of MyList<double>, and two instances of MyList<SampleClass>, where SampleClass is a class I have defined.


 


Output:


2


2


1


1


2


 

                    

Dotnet Related Tutorials

...more

New Dotnet Resources

...more

Copyright © 2010 VisualBuilder. All rights reserved