C # advantages of generics

Source: Internet
Author: User
Introduction to generics

What is generic used? The answer is: if there is no generic type, it will be difficult to create a type-safe set.

C # Is a type-safe language, which allows the compiler (trusted) to capture potential errors ratherProgramIt can only be found during running (it is untrustworthy and often happens after you sell the product !). Therefore, in C #, all variables have a defined type. When you assign an object to that variable, the compiler checks whether the value is correct, if any problem occurs, an error message is displayed.

In. NET 1.1 (2003), this type of security becomes invalid when you are using a set. By.. Net Class Library provides all classes about the set to store the basic type (object), and.. net, all types are inherited by the object base class, so all types can be put in a collection. Therefore, there is no type check at all.

Worse, every time you extract an object from the set, you must forcibly convert it to the correct type. This conversion will affect the performance and produce lengthyCode(If you forget to perform the conversion, an exception will be thrown ). Furthermore, if you add a value type (for example, an integer variable) to the set, this integer variable is implicitly boxed (reducing performance again ), when you extract it from the set, it will be displayed again (performance reduction and type conversion again ).

In earlier versions of the Public Language Runtime Library and C # language, generalization is achieved through forced conversion between types and general basic types of objects, the generic model provides a solution to this limitation. By creating a generic class, you can create a set of secure types during compilation.

You can compile a short program to demonstrate the limitations of non-generic collection classes. This program uses the arraylist collection class in the. NET Framework base class library.ArraylistIs a collection class that is very convenient to use and can be used to store any reference or value type without modification.

System. Collections. arraylist list1 =   New System. Collections. arraylist ();
List1.add ( 3 );
List1.add ( 105 );

System. Collections. arraylist list2 =   New System. Collections. arraylist ();
List2.add ( " It is raining in Redmond. " );
List2.add ( " It is snowing in the mountains. " );

However, this kind of convenience requires a price. AddArraylistAny reference or value type in is implicitly forcibly convertedObject. If the item is of the value type, you must perform the packing operation when adding it to the list, and cancel the packing operation during retrieval. Both forced conversion and packing and unboxing reduce the performance. When circular access is required for large sets, the effect of packing and unboxing is significant.

Another restriction is the lack of compile-time type checks; becauseArraylistAll items are forcibly convertedObjectSo the client code cannot be prevented from performing the following operations during compilation:

System. Collections. arraylist list =   New System. Collections. arraylist ();
// Add an integer to the list.
List. Add ( 3 );
// Add a string to the list. This will compile, but may cause an error later.
List. Add ( " It is raining in Redmond. " );

Int T =   0 ;
// This causes an invalidcastexception to be returned.
Foreach ( Int X In List)
{
T+ =X;
}

AlthoughIntsCombined in oneArraylistThis method is completely legal and sometimes intentional when creating a heterogeneous set, but it is more likely to generate a programming error and cannot be detected until the runtime.

In C # versions 1.0 and 1.1, you can only write your own type-specific set to avoid the risk of common code in the. NET Framework base class library collection class. Of course, since this class cannot be reused for multiple data types, the advantage of generalization will be lost, and you must rewrite this class for each type to be stored.

ArraylistWhat is really needed for similar classes is that the client code specifies the specific data type to be used by these classes based on each instance. In this way, you no longer need to forcibly convertT: system. ObjectAnd also enables the compiler to perform type checks. In other words,ArraylistOneType parameter. This is exactly what generics can provide. InN: system. Collections. GenericGeneric namespaceList <t>To add items to a collection, the operation is similar to the following:

// The. NET Framework 2.0 way to create a list
List < Int > List1 =   New List < Int > ();

// No boxing, no casting:
List1.add ( 3 );

// Compile-time error:
// List1.add ("it is raining in Redmond .");

For client codeArraylistComparedList <t>The only syntax added is Declaration and type parameters in instantiation. Although this slightly adds some encoding complexity, the advantage is that you can create a ratioArraylistA safer and faster list, especially when list items are of the value type.

In summary, generics have the following two advantages over non-generics:

1More secure

In non-generic programming, although everything can be usedObjectTransfer, but the type conversion is inevitable during the transfer process. Type conversion is not safe at runtime. Using generic programming can reduce unnecessary type conversion and improve security. This is not only a value type, but also a reference type. Therefore, it is necessary to use a generic set as much as possible.

2Higher efficiency

In non-generic programming, the simple type is usedObjectThe transfer will cause packing and unpacking operations, both of which are very open-ended. With generic programming, you do not need to pack or unpack the box.

Generic set

Generally, we recommend that you use a generic set, because this provides direct advantages of type security without deriving from the base set type and implementing type-specific members. The following generic types correspond to the existing collection types:

1. List is a wildcard corresponding to arraylist . type.
2. dictionary is a wildcard corresponding to hashtable . type.
3. collection is a wildcard corresponding to collectionbase . type.
4. readonlycollection is a wildcard corresponding to readonlycollectionbase . type.
5. Queue , stack , and sortedlist generic classes correspond to non-generic classes with the same name.
6. The linked list is a list of common links, it provides the insert and remove operations with an operational complexity of O (1) .
7. sorteddictionary is a Sort dictionary, the computation complexity of the insert and search operations is O (log n ) , this makes it sortedlist .
8. keyedcollection is a hybrid type between lists and dictionaries, it provides a method to store objects that contain their own keys.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.