[C # Basic Knowledge series] Topic 6: Generic basics-Why to introduce generics

Source: Internet
Author: User

Introduction:

The previous topic mainly introduced two core features in C #1-delegation and events. However, another important feature introduced in C #2.0 is generics, we will always encounter and use it in common operations. If you are not familiar with some of its related features, let us join in the study of this topic.

 

I. What is generic?

Generic is interpreted as generic in English. Of course, when we query this word, more general meanings are explained. However, some people may think that it is a general type, in fact, there is no conflict between the two. Generic represents a general type, but Microsoft may have an official reference to describe its own features, since generics are generic, generic types are generic types, that is, generic types areModel. In our daily life, we often see a model. For example, the bucket we use in our daily life is a model. We can use bottled water or oil or milk, however, after these are loaded into the bucket, they will have the shape of the bucket (water, milk and oil are invisible), that is, the characteristics of the model.Likewise, generics are the same as barrels. We can use int, string, and class to instantiate generics. after instantiation, int and string types will all have the characteristics of generics.(That is to say, you can use methods defined in generic types, such as list <t> generics. If you use int to initialize them, the list <int> instance can use all the methods defined in the list <t> generic type, and use string to initialize it. It is the same as using bottled water, milk, oil and so on are very similar)

Ii. Why do C #2.0 introduce generics?

We know through the first part what is generic, but why is generic introduced in C #2.0? The answer is, of course, many benefits of generics. Here is an example to illustrate why generic is introduced in C #2.0, and then introduce the benefits of generic.

When we want to write a method to compare two integers, we may soon write the following code:

Public class compare {// return the public static int compareint (INT int1, int int2) {If (int1.compareto (int2)> 0) {return int1 ;} return int2 ;}}

However, when the requirement changes to the method of comparing the size of two strings, We have to implement a method of comparing strings in the class:

// Returns a public static string comparestring (string str1, string str2) {If (str1.compareto (str2)> 0) {return str1;} return str2 ;}

If the requirement is changed to compare the size of two objects, then we need to compare the size of two objects. However, we can see from the requirements that, in the requirement, the comparison types are different, and the implementation method is the same. At this time, we wantNone of these types are generic, We can pass any type as a parameter into this type to instantiate the comparison for a specific type. It is with this idea that Microsoft also came up with this problem in C #2.0, therefore, C #2.0 adds the new generic feature. Generic is a general type, with generics, we can help you solve the problem we just encountered. This solves our first question-why should we introduce generics. The following describes how to implement generics:

 public class Compare<T> where T : IComparable    {        public  static T CompareGeneric(T t1, T t2)        {            if (t1.CompareTo(t2) > 0)            {                return t1;            }            else            {                return t2;            }        }    }

In this way, we do not need to implement a comparison method for each type. We can call the following method in the main function:

 public class Program    {        static void Main(string[] args)        {            Console.WriteLine(Compare<int>.CompareGeneric(3, 4));            Console.WriteLine(Compare<string>.CompareGeneric("abc", "a"));            Console.Read();        }    }

Through the above code, we can certainly understand why generic is introduced in C #2.0. What are the benefits of generic? From the above example, we can see that generics can help us implementCode reuse,Everyone knows that inheritance in Object-Oriented Programming can also be used to reuse code. HoweverCode reuse provided by generics should be exactly"Reuse of algorithms" (I understand that the reuse of algorithms is that we only need to consider how to implement algorithms in implementing a method, without considering the different data types of algorithm operations, such algorithms can be used for better reuse. Generics provide such a mechanism ).

However, in addition to the benefits of code reuse, generics also provide better performance and type security. The following Code explains why these two benefits exist.

Using system; using system. collections; using system. collections. generic; using system. diagnostics; namespace generaldemo {public class program {static void main (string [] ARGs) {stopwatch = new stopwatch (); // non-Generic Array arraylist = new arraylist (); // Generic Array list <int> genericlist = new list <int> (); // start the timer stopwatch. start (); For (INT I = 1; I <10000000; I ++) {genericlist. add (I); // arraylist. add (I);} // End Time stopwatch. stop (); // time used for output timespan Ts = stopwatch. elapsed; string elapsedtime = string. format ("{0: 00 }. {:00} ", ts. hours, ts. minutes, ts. seconds, ts. milliseconds/10); console. writeline ("running time:" + elapsedtime); console. read ();}}}

When we comment out the arraylist. Add (I); line of code to testGeneric ArrayThe running time when data is added. The following is the running time on my machine:

When we comment out the genericlist. Add (I); line of code to testNon-Generic ArrayThe running time of the data added in. The following is the running time on my machine:

From the two results, we can see that the efficiency of adding data to a generic array is much higher than that of a non-Generic Array. If there is a picture and there is a truth, this will fully explainAnother benefit of generics-high performance,HoweverGeneric types also ensure type security.(We All Know that C # is a strong language,Strong typeSpecifies the type of a variable for every definition of a variable.) When we add a value of the string type to this generic genericlist array, the compiler reports an error"Cannot be converted from "string" to "int '"

 

Iii. Summary

This topic mainly shares with you why delegation is introduced in C #2.0 and the benefits of delegation, I believe that through the above introduction, you can have a simple understanding of delegation and a comprehensive understanding of the benefits of generics, there is no reason for this topic of generic high performance. This topic will be introduced to you in the following topic.

 

Related Article

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.