Você está na página 1de 10

C#

Módulo 6: Arrays

1
Arrays

- Todos os elementos são do mesmo tipo


- Os elementos são acedidos utilizando índices inteiros

índice = 0 índice = 4

2
Notação

type[ ] name;

nome da variável
dimensão
tipo de dados

type[ ] name; // Permitido


type name[]; // Não permitido em C#
type[4] name; // Não permitido em C#

3
Dimensão
Vector
long[ ] row;
type[ ] name;
...
Matriz
type[ , ] row[3];
name;
int[ , ] grid;
...
grid[2,3];

Array tridimensional
type[ , , ] name;

etc…
4
Verificação dos limites

row.GetLength(0) == 5 grid.GetLength(0) == 2
row.Length == 5 grid.GetLength(0) == 5
row.Length == 2*5

5
Criação

long[ ] row = new long[4];

Inicialização

Declaração

...
row[1] = 0L;

Atribuição a um elemento do Array

6
Propriedades e métodos
row.Rank
row.Length

int[ ] data = {4,6,3,8,9,3} // Unsorted


System.Array.Sort(data); // Now sorted
System.Array.Clear(data, 0, data.length);
int clone = (int [])data.Clone();
grid.GetLength(0) == 5
int where = System.Array.IndexOf(data,9);

7
Passagem por parâmetro

class Example2 {
static void Main(){
int[] arg = {10, 9, 8, 7};
Method(arg);
System.Console.WriteLine(arg[0]);
}
static void Main(int[] parameter) {
parameter[0]++;
}
}

8
foreach
class Example4 {
static void Main(string[ ] args) {
foreach (string arg in args) {
System.Console.WriteLine(arg);
}
}
}

9
Exercício
int [ ] array;
array = {0, 2, 4, 6}

int [ ] array;
System.Console.WriteLine(array[0]);

int [ ] array = new int[3];


System.Console.WriteLine(array[3]);

int [ ] array = new int[ ];

int [ ] array = new int[3]{0, 1, 2, 3};


10

Você também pode gostar