Change the size of a dimension array in C #

Source: Internet
Author: User

Simulate the redim Statement of Visual Basic and implement it in C #. Only one-dimensional arrays are supported. If you do not need to check the validity of the parameter, only the last four rows are required.ProgramYou can. For details, it is better to throw a rankexception or argumentexception exception when the input array is not 1-dimension (the parameter name can be specified.

1 Using System;
2
3 Static Array redim (array, Int Newlength)
4 {
5 If (Array =   Null )
6 {
7Throw NewArgumentnullexception ("Array");
8}
9 If (Array. Rank ! =   1 )
10 {
11 // Throw new rankexception ("requires a one-dimensional array. ");
12 Throw   New Argumentexception ( " A one-dimensional array is required. " , " Array " );
13 }
14 If (Newlength <   0 )
15 {
16Throw NewArgumentoutofrangeexception ("Newlength","A non-negative number is required.");
17}
18 If (Newlength = Array. length) Return Array;
19
20 Type type = Array. GetType (). getelementtype ();
21 Array newarray = Array. createinstance (type, newlength );
22 Array. Copy (array, 0 , Newarray, 0 , Math. Min (array. length, newlength ));
23 Return Newarray;
24 }

It is also interesting to see the following three constructors. I don't know if it is M $'s negligence. The parameter sequence of the constructor is inconsistent with those of the three similar exceptions, which makes people feel at a loss.

1 Public Argumentexception ( String Message, String Paramname );
2 Public Argumentnullexception ( String Paramname, String Message );
3 Public Argumentoutofrangeexception ( String Paramname, String Message );

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.