Home

In this code snippet, we'll find out what the unchecked keyword does in C#. The unchecked keyword is used to
Javascript Code Snippets Copying An Array
In this post, we'll learn how to copy an array in Javascript. In Javascript, if you assign an array to
JS Code Snippets
This post contains a list Javascript code snippets. In the code snippets, you can find Javascript related topics with a
C# Code Snippets
This post contains a collection of C# related things I learned and projects I did. The C# Code Snippets section
C# Code Snippets Decision Statements
In this code snippet, we will learn how to use the if, else if and switch decision statements in C#.
javascript Code Snippets Breaking out of nested loops
In this post, we'll find out how to break out of multiple loops in Javascript
C# Code Snippets C# Struct
In this code snippet, we'll make a struct in C#. A struct is like a lightweight class. You would use a struct
C# Code Snippets Sealed Keyword
In this code snippet, we'll take a look at the sealed keyword in C#. In the following example, we will
C# Code Snippets 1D 2D 3D Array Looping
This is a tutorial for looping through 1D, 2D and 3D arrays in C#.
Windows 10 IOT Raspberry Pi 3App Deployed
This tutorial covers the deployment of a simple UWP app onto a Raspberry Pi 3 running Windows 10 IOT.

About

In this code snippet, we’ll find out what the unchecked keyword does in C#.

The unchecked keyword is used to suppress arithmetic overflow exceptions. We will try to add two integers whose sum will exceed the size of the integer data type. This will cause an overflow to occur. The overflow would normally throw an exception, but if we wrap the expression with unchecked the exception will get suppressed and the integer will just overflow.

Note: You can also use the checked keyword to explicitly check for arithmetic overflow and throw an exception if it occurs.

Let’s check out the code example below. 

Code:

using System;

namespace Unckecked
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 2147483647;
            int b = 2147483647;

            //This will throw an overflow exception.
            //int c = a + b;

            //This will not throw an overflow exception and will just overflow.
            int c = unchecked(a + b);

            Console.WriteLine(c);

            Console.ReadLine();
        }
    }
}

Resulting output:

Javascript Code Snippets Copying An Array

About

In this code snippet, we’ll learn how to copy an array in Javascript.

In Javascript, if you assign an array to another array using the = assignment operator you won’t actually copy the values from one array into the other. What you will do is make another reference to the first array, so now you just have to variables pointing at the same array.

To copy the actual array you need to do this arrayCopy = […originalArray ].

Let’s see the example below.

Code:

//Make array.
array = [1, 2, 3];

//Copy the array.(well not really)
arrayCopy = array;
//Add an element.
arrayCopy.push(4);

//Print the arrays.
//We would expect the contents of the first array to be 1 2 3 and contents of the second array to be 1 2 3 4.
console.log(array);
console.log(arrayCopy);

//Reset array to original values.
array = [1, 2, 3];

//Now we are actualy copying the array and not just the reference.
arrayCopy = [...array];
//Add element.
arrayCopy.push(4);

//Now we will get the expected output.
console.log(array);
console.log(arrayCopy);

Resulting output:

JS Code Snippets

About

This post contains a list Javascript code snippets. In the code snippets, you can find Javascript related topics with a quick explanation and a code example. I made this collection of code snippets so that if I ever forget something I can just come here to refresh my memory.

Hopefully, you’ll find it useful too.

Note

Here you won’t find a complete set of step by step tutorials but rather a list of quick tutorials with code examples.

If you want to quickly test out some of the code snippets you can copy and paste them into something like jsfiddle.

Javascript Code Snippets

Projects

C# Code Snippets

About

This post contains a collection of C# related things I learned and projects I did. The C# Code Snippets section is where you can find C# and .NET related topics like decision statements, Object-Oriented programming in C#, Threading, Events, Collections, … Meanwhile, under Algorithms and useful bits of code you will be able to find such things as sorting algorithms, quick how-tos, and other useful bits of code that don’t really fit anywhere else. And finally, there is the C# Project section that has my C# projects.

Note

Here you won’t find a complete set of step by step tutorials but rather a list of quick tutorials on a certain topic with code examples. I left out some of the more trivial things and the absolute basics. I only included the things that I thought were the most important or the things I was most likely to forget. If you are looking for complete step by step tutorials I would recommend the #adAmazon LinkMicrosoft Visual C# Step by Step book written by John Sharp. It’s a great book that pretty much covers most things you will ever need to know about C#. Also, there are plenty of great video tutorials on youtube.

C# Code Snippets

Algorithms and useful bits of code

Azure Functions

C# Projects

Here are a couple of projects utilizing C# and some of the concepts from above.
C# Code Snippets Decision Statements

About

In this code snippet, we will learn how to use the if, else if and switch decision statements in C#.

The if decision statement will evaluate the expression provided in the brackets. If the expression is true the first code block executes else the other code block executes.

The switch statement is useful when you have a lot of checks to perform. You pass the value to be compared into the switch statement. Then you can write multiple cases for different possible values. 

Now let’s see how to do it in the code below.

Code:

using System;

namespace DecisionStatements
{
    class Program
    {
        static void Main(string[] args)
        {
            //The if decison statement will evaluate the provided expression. 
            //If the expression is true the first code block executes else the other code block executes.

            //Here are some examples of the if descison statement.
            bool c = true;

            if (c)
            {
                Console.WriteLine("c is true");
            }


            int a = 5;
            int b = 10;

            if (a > b)
            {
                Console.WriteLine("a is bigger than b");
            }
            else
            {
                Console.WriteLine("b is bigger than a");
            }
            

            string str = "Hello World";

            //Multiple checks can be added with the else if statement.
            if (str == "Hello World")
            {
                Console.WriteLine("The string is \"Hello World\"");
            }
            else if (str == "Hello")
            {
                Console.WriteLine("The string is \"Hello\"");
            }
            else
            {
                Console.WriteLine("The string contains something else: " + str);
            }


            //The switch statement is useful when you have a lot of checks to perform.
            string strNumber = "1"; 

            switch (strNumber)
            {
                case "1" : Console.WriteLine("The passed in string is a number.");
                break;

                case "2": Console.WriteLine("The passed in string is a number.");
                break;

                case "3": Console.WriteLine("The passed in string is a number.");
                break;

                case "4": Console.WriteLine("The passed in string is a number.");
                break;

                //If the value passed into the switch statement doesn't match up with any of the cases above the default case will execute. 
                default: Console.WriteLine("The passed in string is not a number between 1 and 4.");
                break;
            }

            Console.ReadLine();
        }
    }
}

Resulting output:

javascript Code Snippets Breaking out of nested loops

About

In this code snippet, we’ll find out how to break out of multiple loops in Javascript. 

Suppose we have an array that contains multiple 2D arrays and we want to find out if each of those 2D arrays contains a specific number. 

The way to do this is to make three nested loops. The first one to iterate through the array of 2D arrays. Then two loops each one for one of the array indexes.

Inside the third loop, there would be an if statement checking if the value at the current indexes is equal to the number we are looking for. If so we would print out the indexes.

But the loops wouldn’t stop looping upon finding the number. To make this more efficient we need to break out of the second and third loop upon finding the number. This is done by “naming”(for a lack of a better term) the loop. Then when we break out of the loop using the break keyword we specify the name of the outer most loop that we want to break out of. Like so break loop2.

To see how exactly this is done let’s take a look at the code below.

Code:

//For this example we will make 3 2D arrays filled with some numbers.
var TwoDArray1 = [
  [3, 2, 5],
  [7, 8, 9],
  [8, 6, 7]
];

var TwoDArray2 = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

var TwoDArray3 = [
  [4, 8, 3],
  [2, 5, 3],
  [1, 6, 5]
];

//Here we'll maeke an array of our arrays.
var ArrayOfArrays = [
  TwoDArray1,
  TwoDArray2,
  TwoDArray3
];

loop1:
for(var i = 0; i < 3; i++){
  //First loop loops through ArrayOfArrays to get the individual 2D array.
  var TwoDArray = ArrayOfArrays[i];
	
  //Loop 2 and 3 loop through the 2D array.
  loop2:
  for(var j = 0; j < 3; j++){
    loop3:
    for(var k = 0; k < 3; k++){
       //Let's say that want to find out if the 2D array contains the number 5.
       //If we find it there is no need to keep looking for it, so we can just move to the next array.
       if(TwoDArray[j][k] == 5){
	  //Print index of the number 5.
	  console.log("I: " +i+ ", J: " +j+ ", K: " +k);
          break loop2; //This will break out of the second loop(and third as well of course).
       }
    }
  }
}
​

Resulting output:

C# Code Snippets C# Struct

About

In this code snippet, we’ll make a struct in C#. 

A struct is like a lightweight class but unlike a class(reference type) it’s value type. This can give you better performance in some cases.

You can use structs as a grouping mechanism to make a small “object” that contains multiple members instead of having them scattered around. If your struct grows too big(has too many properties/methods) you should consider making a class instead.

Note: A struct can’t inherit from another struct.

Let’s see how to make a struct in the code below.

Code:

using System;

namespace Struct
{
    class Program
    {
        static void Main(string[] args)
        {
            //A struct is kind of a "light" version of a class.
            myStruct st = new myStruct();

            st.myMethod();

            Console.WriteLine(st.myProperty);
            Console.ReadLine();     
        }
    }

    struct myStruct
    {
        public string myProperty { get; set; }

        public void myMethod()
        {
            Console.WriteLine("From myMethod.");
        }
    }
}

Resulting output:

C# Code Snippets Sealed Keyword

About

In this code snippet, we’ll take a look at the sealed keyword in C#.

In the following example, we will make a sealed class and a sealed method. Then we’ll try inheriting from the sealed class and overriding the sealed method. As you will be able to see we’ll get an error as sealed methods can’t be overridden and sealed classes can’t be inherited from.

So the whole purpose of the sealed keyword is to “seal” a class or method and thus prevent inheriting/overriding.

Let’s see how to use the sealed keyword in the code example below.

Code:

using System;

namespace Sealed
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

    class MyClass
    {
        public virtual void MyMethod()
        {
            Console.WriteLine("Some text.");
        }
    }

    sealed class MySecondClass : MyClass
    {
        public sealed override void MyMethod()
        {
            Console.WriteLine("Some text.");
        }
    }

    //As you can see we can't inherit from a sealed class.
    class MyThirdClass : MySecondClass
    {
        //As you can see we can't override a sealed method.
        public override void MyMethod()
        {
            Console.WriteLine("Some text.");
        }
    }
}

Result:

Sealed classes can’t be derived from and sealed methods can’t be overridden.
C# Code Snippets 1D 2D 3D Array Looping

About

In this code snippet, we’ll find out how to loop through arrays in C#.

The following C# code snippet contains the code for looping through 1D, 2D, and 3D arrays, filling them up with random numbers and then writing out the values from the arrays.

Code:

using System;

namespace ArrayLooping
{
    class Program
    {
        static void Main(string[] args)
        {
            //Make empty array.(Each "dimension" of a multidimnensional array can have a different size.)
            int[] oneDimensionalArray = new int[10];
            int[,] twoDimensionalArray = new int[10,5];
            int[,,] threeDimensionalArray = new int[10,5,15];

            //Fill the arrays with random numbers.
            oneDimensionalArray = fill1DArray(oneDimensionalArray);
            twoDimensionalArray = fill2DArray(twoDimensionalArray);
            threeDimensionalArray = fill3DArray(threeDimensionalArray);

            //Write out the contents of the arrays.
            Console.WriteLine("1D Array");
            print1DArray(oneDimensionalArray);
            Console.WriteLine("");

            Console.WriteLine("2D Array");
            print2DArray(twoDimensionalArray);
            Console.WriteLine("");

            Console.WriteLine("3D Array:");
            print3DArray(threeDimensionalArray);

            Console.ReadLine();
        }

        public static void print1DArray(int[] array)
        {
            for (int i = 0; i < array.Length; i++)
            {
                Console.Write(array[i]+", ");
            }
        }

        public static void print2DArray(int[,] array)
        {
            //Loop through array. (We use array.GetLength(0) with the index of the "dimension" to get the size.)
            for (int i = 0; i < array.GetLength(0); i++)
            {
                for (int j = 0; j < array.GetLength(1); j++)
                {
                    Console.Write(array[i,j] + ", ");
                }
            }
        }

        public static void print3DArray(int[,,] array)
        {
            //Loop through array. (We use array.GetLength(0) with the index of the "dimension" to get the size.)
            for (int i = 0; i < array.GetLength(0); i++)
            {
                for (int j = 0; j < array.GetLength(1); j++)
                {
                    for (int k = 0; k < array.GetLength(2); k++)
                    {
                        Console.Write(array[i,j,k] + ", ");
                    }
                }
            }
        }

        public static int[] fill1DArray(int[] array)
        {
            Random rnd = new Random();

            //Loop through array.
            for (int i = 0; i < array.Length; i++)
            {   
                //Save a random number form 1-10 into array.
                array[i] = rnd.Next(1, 10);
            }

            return array;
        }

        public static int[,] fill2DArray(int[,] array)
        {
            Random rnd = new Random();

            //Loop through array. (We use array.GetLength(0) with the index of the "dimension" to get the size.)
            for (int i = 0; i < array.GetLength(0); i++)
            {
                for (int j = 0; j < array.GetLength(1); j++)
                {
                    //Save a random number form 1-10 into array.
                    array[i, j] = rnd.Next(1, 10);
                }
            }

            return array;
        }

        public static int[,,] fill3DArray(int[,,] array)
        {
            Random rnd = new Random();

            //Loop through array. (We use array.GetLength(0) with the index of the "dimension" to get the size.)
            for (int i = 0; i < array.GetLength(0); i++)
            {
                for (int j = 0; j < array.GetLength(1); j++)
                {
                    for (int k = 0; k < array.GetLength(2); k++)
                    {
                        //Save a random number form 1-10 into array.
                        array[i, j, k] = rnd.Next(1, 10);
                    }
                }
            }

            return array;
        }
    }
}

Resulting output:

Windows 10 IOT Raspberry Pi 3App Deployed

About

In this tutorial, we will cover the deployment of a simple UWP app onto a Raspberry Pi 3 running Windows 10 IOT. All the app will do is display the current time. The deployment of the app will be done over the network.

Hardware Used

Making the App​

Start by creating a UWP app project in Visual Studio. 
All the UI part consists of is a text block.
The UI in XAML code.
  1. <Page
  2. x:Class="Windows10IOTTestApp.MainPage"
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local="using:Windows10IOTTestApp"
  6. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable="d">
  9.  
  10. <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
  11. <TextBlock x:Name="displayTextBlock" HorizontalAlignment="Left" Margin="66,63,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Height="945" Width="1779" FontSize="150"/>
  12. </Grid>
  13. </Page>

Next is the C# code for the functionality of the app. The code is pretty straight forward. There is a timer that triggers an event every second. That event then calls the getTime() method that gets the current time and displays it in the text block.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices.WindowsRuntime;
  6. using Windows.Foundation;
  7. using Windows.Foundation.Collections;
  8. using Windows.UI.Xaml;
  9. using Windows.UI.Xaml.Controls;
  10. using Windows.UI.Xaml.Controls.Primitives;
  11. using Windows.UI.Xaml.Data;
  12. using Windows.UI.Xaml.Input;
  13. using Windows.UI.Xaml.Media;
  14. using Windows.UI.Xaml.Navigation;
  15. // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
  16. namespace Windows10IOTTestApp
  17. {
  18. /// <summary>
  19. /// An empty page that can be used on its own or navigated to within a Frame.
  20. /// </summary>
  21. public sealed partial class MainPage : Page
  22. {
  23. DispatcherTimer Timer;
  24. public MainPage()
  25. {
  26. this.InitializeComponent();
  27. Timer = new DispatcherTimer();
  28. Timer.Interval = TimeSpan.FromMilliseconds(1000);
  29. Timer.Tick += Timer_Tick;
  30. Timer.Start();
  31. }
  32. private void Timer_Tick(object sender, object e)
  33. {
  34. getTime();
  35. }
  36. private void getTime()
  37. {
  38. DateTime dt = DateTime.Now;
  39. displayTextBlock.Text = dt.ToString("HH:mm:ss");
  40. }
  41. }
  42. }

Testing the App on PC

This is what our app is supposed to look like.

Deploying the App to the Raspberry Pi​

Before deploying  the app change the architecture from x86/64 to ARM.
For the device select Remote Machine.
Go to project properties.
Select  Debug, under Start options choose remote machine for the target device, enter the IP of your windows IOT device and select Universal for authentication mode.
Now just click the green debug button or press F5 and your app will be deployed to your device. It might take quite a long time to deploy (1-2 minutes).