Popular Posts

Nov 16, 2012

Generics Classes - C#

Generic classes have type parameters. Several separate classes in a C# program, each with a different field type in them, can be replaced with a single generic class. The generic class introduces a type parameter. The most common use for generic classes is with collections like linked lists, hash tables, stacks, queues, trees, and so on.This becomes part of the class definition itself.

In this example, the letter T denotes a type that is only known based on the calling location. The program can act upon the instance of T like it is a real type, but it is not.

Create a console project then create a class  MyGenericClass.cs

public class MyGenericClass
        //Generic variables 
        private T d1;
        private T d2;

        public MyGenericClass() { }

        //Generic constructor    
        public MyGenericClass(T a1, T a2)
            d1 = a1;
            d2 = a2;
        //Generic properties 
        public T D1
            get { return d1; }
            set { d1 = value; }

        public T D2
            get { return d2; }
            set { d2 = value; }

        public void ResetValues()
            d1 = default(T);
            d2 = default(T);


In Program.cs file type the following CODE:

//contain int values 
MyGenericClass c1 = new MyGenericClass(5, 10); 
           // reset values to 0 
          // Console.WriteLine();
            //contain  string values
MyGenericClass c2 = new MyGenericClass("a", "b");
            //reset values to null 

For more visit http://msdn.microsoft.com/en-us/library/sz6zd40f.aspx

No comments:

Post a Comment