Home > Articles > Programming > C#

Magic of Arrays Using C#

If you store data for many customers in memory and then send it in batches to a database, how can you optimize the process? Learn the importance of arrays and how to use specific types of arrays to solve particular problems.
Like this article? We recommend

Like this article? We recommend

Arrays are always a part of any high-level programming language. We can think of arrays as the first step to complex data structures or call them basic data structure. When we start to talk about the user-defined data types (abstract data types) in any language, we first talk about arrays, although the user does not really have the freedom to alter the basic structure of the data type. Still, there are some handy things we can do with arrays.

Well! If you are into programming, you are familiar with the concept of arrays by programming in C, C++, Java, or any other language. Moreover, we usually feel that there is nothing special about arrays; most of us ignore the power of arrays, and use them as normal primitive data types. This article discusses when and why to use a certain type of array to solve a certain problem.

In most languages, what we know about arrays include the following:

  • Linear type data structure

  • Contiguous memory collection of a particular data type (primitive or abstract)

  • Control over elements through subscripts

  • Early time (static) and late (dynamic) time binding

C# gives a bit more to work with, however. This article discusses two types of arrays in depth, in the context of C#:

  • Multi-dimensional arrays

  • Jagged arrays

Before jumping directly to the multi-dimensional and jagged arrays, we'll take a quick look at the basic concepts of C# arrays. If you are already familiar with the syntax of C# arrays and its benefits, you can skip the next section ("What's Special about Syntax"), but if you want to know how syntax can improve things, read the following section.

What's Special about Syntax

Arrays Declaration

We can declare an array in different languages, including C#.

int arr[5] ;  // Declaring an array in C or C++
int[] arr ;  // Declaring an array in C#

C# syntax is very similar to C and C++, except that the [] symbol is placed before the identifier.

Syntax provided by C# will be a bit hard to adapt to by programmers coming from C, C++, or other similar languages because there is no backward-compatibility with other vendor languages' syntax, including Microsoft. But, of course, there must be some strong reason...

What if we want to declare four arrays?

int arr1[5], arr2[5], arr3[5], arr4[5] ; // Declaring arrays in C or C++
int[] arr1, arr2, arr3, arr4 ;  // Declaring arrays in C#

Yes! We don't need to repeatedly insert the '[]' symbol in front of every identifier to prove it's an array because in C# we assume that 'int[]' is an integer-array data-type that can be used as any other normal primitive data type. But when I explained this to one of my friends, he said, "Okay! We agree that this is a positive point, but with the syntax of C and C++-like languages, we can also insert a simple integer variable declaration in-between the arrays declaration." For the sake of simplicity, the following example answers my friend:

// Declaring arrays and integer variable 'var' in C or C++ 
int arr1[5], arr2[5[], var, arr3[5], arr4[5] ;

// Wrong declaration in C# for our purpose
int[] arr1, arr2, var, arr3, arr4 ; 
// Declaring arrays and integer variable 'var' in C#

As you can see, this declares an integer type variable 'var' in C and C++ in a normal way in the same line, whereas in C#, I have written it as a wrong declaration.

What's wrong with C# declaration for integer variable 'var'?

We can see in the beginning of declarations in C and C++-like languages that the keyword is 'int'; whereas in C# declarations it is started with 'int[]', not 'int'—and that makes a great difference. In the syntax of C#, in which 'int[]' can be considered as an integer-array data type, every variable is an integer array; in the case of C and C++-like languages, every variable is an integer until we specify the '[]' symbol in front of the identifier. This is why 'var' is not a simple integer in a C# declaration; instead, it is also an array like other arrays.

So, what if we really we want to declare an integer variable and four arrays in C#? The solution is the following:

// C# declarations
int[] arr1, arr2, arr3, arr4 ;
int var ;

This is the way we can declare four arrays in a different block with an 'int[]' data type and an integer-only declaration with an 'int' data type. So, in all cases (C, C++, and C#), we have declared four arrays (arr1, arr2, arr3, arr4) and one integer variable ('var'). In C#, however, we have to declare our integer variable 'var' in a different block (line here), but we get a loss of flexibility and waste of time in that case.

Is this really a waste of time, or is something hidden? Yes! This gives us a better programming approach, which is very important to the programmer and to his company, too.

The readability of programs is the success key of any IT project. In the absence of certain rules imposed on the programmers to maintain the readability of the program, companies as well as programmers suffer when they go back to their source code after a long time. Also, if a programmer leaves a company, then the replacement programmer has to fight a lot to understand the source code written by the old programmer. In this case, companies have to invest lots of energy to get things back on the right track, and sometimes they have to scrap most of the work done by the old programmer (again, lots of time and money wasted).

For example, suppose we want to search all the integer-type variables defined in the program (not arrays). In C and C++-like language syntax, we have to go through every line that starts with the 'int' keyword; then we have to identify the integer variables and ignore the array declarations. But in the case of C# syntax, this is crystal-clear. If there is an 'int[]' at the beginning of the line, then all variables are integer arrays; in the case of the 'int' keyword, all the variables are integer variables only. This really saves a lot of time, not only for a newly employed programmer who is fighting to understand the code written by his predecessor. It can also help the programmer when he returns to his code after a long time or when he is debugging his code.

After this discussion of array syntax, we can easily assume that we have the same benefits with two- dimensional or multi-dimensional arrays. The syntax is the following:

int[ , ] arr ; //Two Dimensional array declaration
int[ , , ] arr ; //Three (Multi) Dimensional array declaration

And accessibility is the same, as the syntax shows. For example, to access the second element of the second row (if this exists), the syntax is arr[1,1] ;.

The other member of the family of the array series is the jagged array. Jagged arrays are simply arrays of arrays (jagged arrays contain other arrays inside).

int[][] arr ; //Declaring jagged array : array of arrays

Although this syntax may look familiar to C and C++ programmers for two-dimensional (multi-dimensional) arrays, it is actually quite different from multi-dimensional arrays in C#.

The following is a summary of some array declarations:

int[] a1;     // single-dimensional array of int
int[,] a2;     // 2-dimensional array of int
int[,,] a3;     // 3-dimensional array of int
int[][] j2;     // "jagged" array: array of (array of int)
int[][][] j3;   // array of (array of (array of int))

Memory Allocation

In the case of memory allocation, to really store the data into an array, we use the keyword 'new', as we do to instantiate an object. (When using the 'new' keyword, we are allocating memory at run time, not at compile time; C# uses static bindings only when an array has been initialized.).

// In case of single dimentional array to store 5 integer type elements
int[] arr = new int[5] ; 

// In case of two dimensional array to allocate memory 
// for 3 rows and 2 columns
int[ , ] arr = new int [3,2] ; 

For a multi-dimensional array, the syntax is the same as for a two-dimensional array, while the number of indices inside '[]' depends on the dimensions of the array.

For example, for a three-dimensional array:

//Allocating memory for three dimensional array
int[ , , ] arr = new [3,2,2] ; 

Memory allocation is different for jagged arrays:

//In case of jagged array to place 3 rows where we can allocate the memory 
//For different number of columns in every row as shown in following lines
int[][] arr = new int[3][] ;
arr[0] = new int[2] ; // 2 columns in first row
arr[1] = new int[1] ; // 1 column in second row
arr[2] = new int[3] ; // 3 columns in third row

The following is a summary of array initializations:

int[] a1 = new int[] {1, 2, 3};
int[,] a2 = new int[,] {{1, 2, 3}, {4, 5, 6}};
int[,,] a3 = new int[10, 20, 30];
int[][] j2 = new int[3][];
j2[0] = new int[] {1, 2, 3};
j2[1] = new int[] {1, 2, 3, 4, 5, 6};
j2[2] = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020