The .NET and COM Interoperability Handbook (Integrated .Net)
Creating and Using an Array in C# Working with Arrays in C# is simpler and less error-prone than C and C++. Arrays in C# are objects that support the properties shown in Table 4-8. Table 4-8. A sample of the properties in System.Array
The C# array class contains the methods shown in Table 4-9. Table 4-9. A sample of the methods in System.Array
As you can see from looking at the methods and properties supported by the array class, arrays are full-featured collections in C#. You can perform a shallow or deep copy, search for the first or last occurrence of a specified value, reverse the order of the elements in the array, or sort the elements in the array. Using an array is similar to the way that you would use an array in C++. The following code demonstrates how to use arrays in C#: namespace ArrayApp { using System; using System.Text; internal class Employee { public Employee(string name) { this.name=name; } public string name; } public class TestArray { public static int Main(string[] args) { // An array of value types int[] intArray=new int[20]; // An array of reference types Employee[] empArray=new Employee[2]; // An initialized array string[] strArray= {"A", ".NET","Primer"}; int i; for (i=0;i<20;i++) intArray[i]=i; empArray[0]=new Employee("Alan Gordon"); empArray[1]=new Employee("Tamber Gordon"); Console.WriteLine(intArray[1]); Console.WriteLine(strArray[1]); Console.WriteLine(empArray[1].name); return 0; } } } You can also create multidimensional arrays in C#. The following example program demonstrates how to declare and use multidimensional arrays: namespace ArrayApp { using System; using System.Text; internal class Employee { public Employee(string name) { this.name=name; } public string name; } public class TestArray { public static int Main(string[] args) { float[,,] fltArray=new float[2,3,4]; Employee[,] empArray=new Employee[2,3]; string[,] strArray= { {"A", ".NET","Primer"}, {"COM","COM+","Primer"}}; int i, j, k; for (i=0;i<2;i++) for (j=0;j<3;j++) for (k=0;k<3;k++) fltArray[i,j,k]= i*1.5f+2.5f*j+3.5f*k; empArray[0,1]=new Employee("Alan Gordon"); empArray[1,1]=new Employee("Tamber Gordon"); Console.WriteLine(fltArray[1,1,1]); Console.WriteLine(strArray[1,2]); Console.WriteLine(empArray[1,1].name); return 0; } } } |
| | |
| Team-Fly |
| Top |