πŸ“’
SDV503
  • SDV503
  • Command Prompt
    • Windows Command Prompt
    • Mac OS Terminal
  • GIT & GITHub
    • GitHub
    • Git
      • Git Workflow
        • Forking Workflow
  • README
    • How to write a readme.md file?
    • Write a better README.me
    • Generate a README for GitHub Repo Quickly
  • Code-comments
    • Clean Comments
    • Writing Comments in a Good way
  • Pair Coding
    • What is Pair Coding?
    • Pair Programming Experience
  • Programming?
    • What is Programming?
    • What Is A Programming Paradigm?
    • JavaScript Programming Paradigms
  • Number Systems
    • Decimal and Binary numbers
  • JavaSCript
    • Introduction To JavaScript
      • The JavaScript Engine
  • JS Call Stack
    • JavaScript call stack
    • JavaScript & Memory
      • Memory Leaks in JavaScript
    • Execution Context and Execution Stack in Javascript
      • Javascript Execution Context and Hoisting
  • JavaScript Variables
    • Introduction to JS Data Types
    • Primitive and Non-Primitive
    • Operator precedence and associativity
      • JS Operators Part One
      • JS Operators Part Two
      • JS Operators Part Three
    • Clean Code for JS Variables
  • JavaScript Scopes
    • Scope (Chain) Visualized
  • Javascript β€Šβ€”β€Šthis keyword
  • JavaScript Data Types
    • More JavaScript Data Types
  • JavaScript Expressions and Statements
  • if/else, switch and ternary operator
    • If/Else statement
  • Switch Statement
  • Ternary Operator
  • JavaScript Loops
    • Loops in JavaScript
      • Trouble With Loops
  • Objects
    • JavaScript Objects
      • Prototypal Inheritance Visualized
      • JavaScript Number Object
      • JavaScript String Object
  • Functions
    • JavaScript Function Part One
    • JavaScript Function Part Two
    • Immediately Invoked Function Expressions ~ IIFE
    • JS => Arrow Functions
    • JavaScript Callback
    • Hoisting in JavaScript
      • Hoisting Visualized
    • Recursion Functions
    • Curry and Function Composition
  • JavaScript Features
    • JSpread Operator
    • JavaScript Built-in Functions & Objects
  • Data Structures&Algorithms
    • JavaScript’s Data Types
    • Data Structures in JavaScript
      • Introduction to Big O Notation
      • Big O Notation in Javascript
      • Linked Lists
        • Linked Lists β€” 2
      • Hash Tables
      • Stack & Queue
  • TLDR
    • Single quotes (β€˜ ’) and double quotes (β€œ ”) in JavaScript
  • ES6
    • Generators and Iterators
    • Javascript Classes
    • JavaScript closures
    • JavaScript Promises & Async/Await
      • Event Loop Visualized
  • C#
    • What does C#? (C Sharp)
    • C# vs JavaScript
    • What Is The Difference Between C#, .NET, ASP.NET, Microsoft.NET, and Visual Studio?
    • What is the .NET Framework?
    • Methods and Properties of Console Class in C#
    • Datatypes in C#
    • C# Code Comments
    • The if statement
    • The switch statement
    • Loops
    • Comparison operators
    • Addition assignment operators
    • The String Interpolation Operator
    • Arrays
    • Lists
    • Dictionaries
Powered by GitBook
On this page

Was this helpful?

  1. C#

Arrays

Arrays works as collections of items, for instance strings. You can use them to gather items in a single group, and perform various operations on them, e.g. sorting. Besides that, several methods within the framework work on arrays, to make it possible to accept a range of items instead of just one. This fact alone makes it important to know a bit about arrays.

Arrays are declared much like variables, with a set of [] brackets after the datatype, like this:

string[] names;

You need to instantiate the array to use it, which is done like this:

string[] names = new string[2];

The number (2) is the size of the array, that is, the amount of items we can put in it. Putting items into the array is pretty simple as well:

names[0] = "John Doe";

But why 0? As it is with so many things in the world of programming, the counting starts from 0 instead of 1. So the first item is indexed as 0, the next as 1 and so on. You should remember this when filling the array with items, because overfilling it will cause an exception. When you look at the initializer, setting the array to a size of 2, it might seem natural to put item number 0, 1 and 2 into it, but this is one item too much. If you do it, an exception will be thrown. We will discuss exceptions in a later chapter.

Earlier, we learned about loops, and obviously these go great with arrays. The most common way of getting data out of an array, is to loop through it and perform some sort of operation with each value. Let's use the array from before, to make a real example:

using System;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
    static void Main(string[] args)
    {
        string[] names = new string[2];
                
        names[0] = "John Doe";
        names[1] = "Jane Doe";
                
        foreach(string s in names) {
        Console.WriteLine(s);        
        Console.ReadLine();
        }
        
    }
    }
}

We use the foreach loop, because it's the easiest, but of course we could have used one of the other types of loop instead. The for loop is good with arrays as well, for instance if you need to count each item, like this:

for(int i = 0; i < names.Length; i++)
    Console.WriteLine("Item number " + i + ": " + names[i]);

It's actually very simple. We use the Length property of the array to decide how many times the loop should iterate, and then we use the counter (i) to output where we are in the process, as well as get the item from the array. Just like we used a number, a so called indexer, to put items into the array, we can use it to get a specific item out again.

I told you earlier that we could use an array to sort a range of values, and it's actually very easy. The Array class contains a bunch of smart methods for working with arrays. This example will use numbers instead of strings, just to try something else, but it could just as easily have been strings. I wish to show you another way of populating an array, which is much easier if you have a small, predefined set of items that you wish to put into your array. Take a look:

int[] numbers = new int[5] { 4, 3, 8, 0, 5 };

With one line, we have created an array with a size of 5, and filled it with 5 integers. By filling the array like this, you get an extra advantage, since the compiler will check and make sure that you don't put too many items into the array. Try adding a number more - you will see the compiler complain about it.

Actually, it can be done even shorter, like this:

int[] numbers = { 4, 3, 8, 0, 5 };

This is short, and you don't have to specify a size. The first approach may be easier to read later on though.

Let's try sorting the array - here's a complete example:

using System;
using System.Collections;
namespace ConsoleApplication1
{
    class Program
    {
    static void Main(string[] args)
    {
        int[] numbers = { 4, 3, 8, 0, 5 }; 
              
        Array.Sort(numbers);        
        foreach(int i in numbers)
        
        Console.WriteLine(i);        
        Console.ReadLine();
    }
    }
}

The only real new thing here is the Array.Sort command. It can take various parameters, for various kinds of sorting, but in this case, it simply takes our array. As you can see from the result, our array has been sorted. The Array class has other methods as well, for instance the Reverse() method. You can look it up in the documentation to see all the features of the Array class.

The arrays we have used so far have only had one dimension. However, C# arrays can be multidimensional, sometimes referred to as arrays in arrays. Multidimensional arrays come in two flavors with C#: Rectangular arrays and jagged arrays. The difference is that with rectangular arrays, all the dimensions have to be the same size, hence the name rectangular. A jagged array can have dimensions of various sizes. Multidimensional arrays are a heavy subject, and a bit out of the scope of this tutorial.

PreviousThe String Interpolation OperatorNextLists

Last updated 4 years ago

Was this helpful?