In the previous tutorials, we discussed arrays in C# and multidimensional array in C# . In this lesson, we are going to learn jugged arrays in C# programming. The jagged array is an array whose elements are arrays.
In simple words, every array stored element. In C#, the element of arrays is arrays. The concept is known as jugged array. In the previous tutorial, we discussed two dimensional. The jugged array elements can be different dimension and size.
The declaration of jugged array will help you understand the jugged array concept in C# .
int[][] my_array= new int[2][]; int[][] my_array=new int[3][ ];
Declaring the jugged array is not initializing jugged array. Let's initialize jugged array in C#.
my_array[0] = new int[5] { 1, 3, 5, 7, 9 }; my_array[1] = new int[4] { 2, 4, 6, 8 }; my_array [0]=new int {3,5};
my_array [1]=new int {3,5,6,3}; my_array [2]=new int {3,5,9};
In this array define an only number of rows not the number of columns.
Checked operator
If we mark a block of code as checked the CLR will enforce overflow checking once throw an exception if an overflow occurs.
Unchecked operator
It is used to suppress overflow checking, in this case, no execution will be raised but we will lose the data.
Example
byte b=255;
checked
{ b++; //message will display when the value of b goes out of range.
}
If unchecked no message will come and data will be lost.
using System;
namespace JuggedArrayApplication {
public class MyArray {
public static void Main(string[] args) {
/* a jagged array of 4 array of integers*/
int[][] x = new int[][]{new int[]{1,1},new int[]{2,2},
new int[]{3,3},new int[]{ 4, 4 } };
int i, j;
/* output each array element's value */
for (i = 0; i < 4; i++) {
for (j = 0; j < 2; j++) {
Console.WriteLine("a[{0}][{1}] = {2}", i, j, x[i][j]);
}
}
}
}
}
a[0][0] = 1 a[0][1] = 1 a[1][0] = 2 a[1][1] = 2 a[2][0] = 3 a[2][1] = 3 a[3][0] = 4 a[3][1] = 4