General Solutions for using c # Generic variables as operands

Source: Internet
Author: User

Problem Source: in c # programming, some numeric primitive types such as Int16, Int32, Int64, and Decimal are often involved in addition, subtraction, multiplication, division, and so on. For example, we often write the following method, which is used to calculate the sum of the numbers from 0 to the 32-bit integer input (no special circumstances such as overflow are considered ):

1 internal static Int32 Sum( int num) 2 { 3      Int32 sum = 0; 4      for (Int32 i = 0; i < num; i++) 5      { 6          sum += i; 7      } 8      return sum; 9 }

Similarly, if we need to return the type and input type to other primitive types, such as Decimal and Int64, normally we will modify the return and input parameter types in the above Code, for example, you can sum Int64 as follows:

1 internal static Int64 Sum(Int64 num) 2 { 3      Int64 sum = 0; 4      for (Int64 i = 0; i < num; i++) 5      { 6          sum += i; 7      } 8      return sum; 9 }

But how many different primitive numeric types do you need to write such a method (here we do not consider the mutual conversion between some numeric primitive types), resulting in method expansion and code bloated? After analyzing the code above, we found that the number of parameters and the calculation format are very similar. Without a doubt, we will think of abstracting a common generic method to solve the Calculation Problem of the numeric primitive type.

In <CLR Via C #>, jeffrey Richter gives an example and tries his best to implement the following generic method to implement a generic type variable as the operand:

01 internal static class UsingGenericTypeVariablesAsOperands 02 { 03      private static T Sum<T>(T num) where T : struct 04      { 05          T sum = default (T); 06          for (T n = default (T); n < num; n++) 07              sum += n; 08       

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.