Namespaces:
Using System.Collections;
Class Program
{
Make a comparison
static void Main (string[] args)
{
New Object
CLS A1 = new CLS ();
CLS A2 = new CLS ();
Storing objects
list<cls> testfanxing = new list<cls> ();
Testfanxing. ADD (A1);
ArrayList Testarray = new ArrayList ();
Testarray. ADD (A2);
Fetch Object
Cls B1 = testfanxing[0];
Cls B2 = testarray[0];//this sentence error! Instead: CLS b2 = (CLS) testarray[0]; it passes normally, but type casts are used.
What are the benefits of generics?
1. Avoids forcing type conversions and causes poor code readability.
2. Now that you have a type cast, the problem is that the type cast might be time-consuming to use for boxing and unpacking procedures.
3. Because of the forced type conversion, it may not be wrong to compile, but it is possible to run the code with errors due to conversion failure. This is the non-security code we're talking about.
}
}
Class Cls
{ }
In simple terms, generics are limited to the type of operation.
Speaking in Microsoft's words:
Any reference or value type added to ArrayList is implicitly cast upward to Object. If the item is a value type, it must be boxed when it is added to the list, and the unboxing operation is performed when it is retrieved. Both casting and boxing and unboxing operations degrade performance, and the effect of boxing and unboxing is noticeable in cases where large collections must be cycled. ”
C # List