Tag Archives: c

Methods in C#

A method, also known as a function, is a module of code that a programmer can create and then call on later on in the program. Many methods already exist in programming languages such as C# but the programmer also has the ability to make their own. A method will usually perform a single task. Many methods can work together to achieve a goal.

Methods should have descriptive names (they should represent an action and are usually in the form of a verb). Spaces cannot be used in method names and you should always avoid use of special characters eg. $%^!@. The method name itself should also not contain brackets because brackets are used for parameters. When you create a new method, the method name should be unique and not already exist in the language (it should not be a reserved word that is used for a statement or method).

Method names should follow a consistent naming convention throughout your code eg. using camel case or mixed case. Examples of suitable method names include CalculateScore, AddNumbers, MultiplyNumbers, GetUserDetails, etc.

Watch the video below and then scroll down for examples and sample code.

Creating methods

Lets break up the method into its different components and look at each component…

What is an access modifier?

Access modifiers include public and private (or just left empty). Public means other parts of the program can see and use this method. If we don’t want that we use private instead or no access modifier (leave it out).

What is a return type?

Methods are able to return a variable back to the code that called it known as the return type. If a method returns an integer value then the return type is an int and if a method returns a true or false value then the return type is a bool. Even if the method doesn’t return any value, it still has a return type. If the method doesn’t return a value, then its return type is void (which means nothing). You might notice that many functions have a return type of void.

What are parameters?

In the same way that methods can pass a variable back to the code that called it, the calling code can pass variables into the method. These variables are known as parameters. The variables that are passed into the method are identified in the parameter list part of the method (inside the brackets). When you specify a parameter you must specify the variable type and the name. If there are no parameters, then the brackets are left empty.

Below is an example of a method in C# for a calculator that is used to add two numbers together. There are two parameters in this method (separated by commas). The parameters in this method are num1 and num2. These are the two numbers that will be added together (they are of the float data type). Notice that the return type is also float meaning that the result of this method (the sum of num1 and num2) will be returned as a float value.

public static float AddNumbers(float num1, float num2)
 {
   float total = num1 + num2;
   return total;
 }

The method above will add two numbers together (the two parameters num1 and num2) and then return the answer as a float back to the part of the program that called the method.

The word static means that this particular method is associated with the class, not a specific instance (object) of that class. What this means is that you are able to call a static method without actually creating an object of the class.

Many methods have the word void in their declaration. The word void basically means that the method will not return any value to the part of the program that called it.

Using methods

Once you have created a method the next thing to do is use it. Using a method is known as calling or invoking a method. To call a method that was named AddNumbers, you would write:

AddNumbers();

If the method contained a parameter or multiple parameters (eg. the values 5 and 10), then they would be included inside the brackets like this:

AddNumbers(5,10);

The below example shows how to call a method and pass variables into the method. You do not need to write int inside the brackets where the function is called.

int number1 = 10;
int number2 = 30
AddNumbers(number1,number2);

When you call a method you do not need to provide the variable type with the variable that is being passed into the method. If the method AddNumbers() in the example code above returns a value, then it should be stored in a variable or used in a statement, for example:

int result = AddNumbers(5,10);

Sample code

Here is an example using parameters and a return type of void. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      AddNumbers(5, 10);
    }
    public static void AddNumbers(int num1, int num2)
    {
      int total = num1 + num2;
      Console.WriteLine("The sum of the two numbers is " + total);
    }
  }
}

Here is an example using parameters and a return type of int. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int answer = AddNumbers(5, 10);
      Console.WriteLine(answer);
    }
    public static int AddNumbers(int num1, int num2)
    {
      int total = num1 + num2;
      return total;
    }
  }
}

Here is an example using no parameters. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int answer = AddNumbers();
      Console.WriteLine(answer);
    }
    public static int AddNumbers()
    {
      int total = 5 + 10;
      return total;
    }
  }
}

Foreach loops in C#

This tutorial explains how to use the foreach loop to go through each element in an array. A foreach loop is simpler and easier to use than a for loop if you want to loop through each and every element in an array. There is no need to use a counter, specify an increment, or a condition. The foreach loop will simply loop through every element in the array.

Foreach loops are written in a way that is easy to understand, for example:

foreach (string item in itemsList){
   Console.WriteLine(item);
}

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};

      // Store length of names array in variable
      int arrayLength = names.Length;

      // Go through each name in names array and display on new line
      foreach (string name in names) {
        Console.WriteLine(name);
      }
      // Wait for user input before quitting program
      Console.ReadLine();
    }
  }
}

Next tutorial: Methods

Arrays in C#

Arrays are basically a list of items of the same type that are grouped together in a single container. Unlike variables which can only contain one value at a time, arrays can contain many different values of the same type (eg. string, or integer). This tutorial explains how to create arrays, access elements in an array, and use for loops to work through the elements in arrays.

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};
      // Create an array of int type
      int[] ages = {26,18,49,33};
      // Display second item in names array (array indexing starts at 0)
      Console.WriteLine(names[1]);
      // Display fourth item in ages array
      Console.WriteLine(ages[3]);
      // Store the names array's length (number of elements in array) in variable
      int arrayLength = names.Length;
      // Display names array's length
      Console.WriteLine(arrayLength);
      // Go through each element in names array and check if Sam exists in array
      for (int i = 0; i < arrayLength; i++) {
        if (names[i] == "Sam") {
          Console.WriteLine("Sam is here!");
        }
      }
    }
  }
}

Next tutorial: Foreach loops in C#

Do while loops in C#

A do while loop is a type of loop which repeats code while a certain condition evaluates to true. However, unlike a while loop which tests the condition first, a do while loop tests the condition after running instructions inside the loop. This means that the code inside the loop will always run at least once even if the condition evaluates to false. This is an example of post-test repetition.

Watch the video below and then scroll down to see the sample code.

Sample code

Take a look at the sample code below. The counter is set to 99 and the condition being tested is counter < 10. However, the code inside the loop runs the first time even though the condition evaluates to false because a do while loop runs the code inside the loop before testing the condition (meaning that the instructions inside the loop will always run at least once).

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int counter = 99;
      do
      {
        Console.WriteLine("Counter is: " + counter);
        counter++;
      } while(counter < 10);
      Console.ReadLine();
    }
  }

}

Next tutorial: Arrays in C#

For loops in C#

In this tutorial you will learn how to use the for loop to repeat sections of code in the C# language. For loops are useful for when you want to repeat code a certain number of times. They are also very useful for efficiently working through all the elements in an array or going through each character in a string. For loops have a built in counter, condition, and increment. Watch the video below and then scroll down for the sample code.

Sample code

Example 1 – using for loop as simple simple counted loop

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      for (int i = 0; i < 10; i++)
      {
        Console.WriteLine("Counter is: " + i);
      }
      Console.ReadLine();
    }
  }

}

Example 2 – using for loop to go through each character in string

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      string word = "dog";
      for (int i = 0; i < word.Length; i++)
      {
        if (word[i] == 'a')
        {
          Console.WriteLine("This word contains the letter a");
        }
      }
      Console.ReadLine();
    }
  }

}

Next tutorial: Do while loops in C#

While loops in C#

This tutorial explains how to write a while loop in the C# language. A while loop is used to repeat a section of code while a condition evaluates to true. For example, keep asking for a password while the password being entered is wrong, or keep displaying a message a number is less than a certain number, or keep moving a character in a game to the right side of the screen while the right arrow key is being pressed on the keyboard.

A while loop is a pre-test loop meaning it tests a condition before running code inside the loop. If the condition being tested never evaluates to true then the loop will not run. After each iteration of a loop, if the condition being tested evaluates to false then the loop will exit and the rest of the program will run. It is important that you allow loops to eventually end by specifying a condition that will eventually evaluate to false, otherwise you will end up having an ‘infinite loop’ causing your program to crash.

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int counter = 0;
      while (counter < 10)
      {
        Console.WriteLine("The counter is " + counter);
        counter--;
      }
      Console.ReadLine();
    }
  }

}

Next tutorial: For loops in C#

Converting variable types in C#

This tutorial explains how to convert variable types in the C# language (eg. convert from string to integer or float, or convert from integer or float to string). Here is a summary of the methods used:

  • float.Parse() – converts to float type
  • int.Parse() – converts to int type
  • .ToString() – converts to string type

Watch the video below and then scroll down to see the sample code.

Example of converting from string to float:

float myFloatVariable = float.Parse(myStringVariable);

Example of converting from string to int:

int myIntVariable = int.Parse(myStringVariable);

Example of converting from int or float to string:

string myStringVariable = myFloatVariable.ToString();

Here is the full sample code from the tutorial video:

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      Console.WriteLine("Enter your name: ");
      string username = Console.ReadLine(); // store user input as string
      Console.WriteLine("Hello there, " + username);

      Console.WriteLine("Enter two numbers");
      float num1 = float.Parse(Console.ReadLine()); // convert user input from string to float
      float num2 = float.Parse(Console.ReadLine()); // convert user input from string to float
      Console.WriteLine("The result is: " + (num1 + num2)); // display string of text and float result 

      int num3 = 5;
      int num4 = 10;
      Console.WriteLine(num3.ToString() + num4.ToString()); // convert int to string
    }
  }
}


Next tutorial: Making comparisons in C#

Variables, constants and data types in C#

In this tutorial you will learn about variables, constants and data types in the C# language.

Variables are like containers that can store data that you will use in your application. Variables can be given a value to store that can be accessed and modified or updated throughout the program whereas constants are given a value that can’t be changed in another part of the program – in other words the variable’s value is constant throughout the program.

Variables and constants must be given a unique name (starting with lowercase letter and cannot contain spaces or special characters) and they must have a certain type. A type specifies the kind of data that a variable can hold. A variable that has a name and a type can then have a value assigned to it.

Take a look at the following line of code:

int myNumber = 5;

The line of code above says that a new variable called myNumber is being declared. It is of the int (integer) type and is assigned a value of 5.

The table below shows the data types available in the C# language.

Type Description
int The integer data type stores positive or negative whole numbers eg. 5
float The float data type stores floating point numbers (numbers with decimal places).
double The double data type stores floating point numbers but with double precision.
bool The bool (short for Boolean) data type stores true or false values only eg. true
char The char data type stores a single character such as a letter, number, space or special character (eg. a, 1, !).  A char value is written in single quotes eg. ‘a’.
string The string data type stores letters, numbers and other characters in the form of words or sentences. A string value is written inside double quotes eg. “Hello World”.

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      const string mySentence = "The quick brown fox jumps over the lazy dog.";
      Console.WriteLine(mySentence);

      int myNumber = 5;
      Console.WriteLine(myNumber);

      float myFloat = 15.279f;
      Console.WriteLine(myFloat);

      double myDouble = 150.24649;
      Console.WriteLine(myDouble);

      bool myBool = false;

      Console.ReadLine();
    }
  }
}

Next tutorial: Arithmetic and assignment operators

Introduction to C#

Welcome to the Coding in C# tutorial series. While working through these tutorials you will learn the fundamentals of object-oriented programming and develop the skills to write your own applications using the C# programming language.

C# is a modern, general purpose, object-oriented programming language used to develop desktop applications on both Windows and Mac platforms, mobile apps for iOS, Android and Windows Phone platforms, as well as games for desktop, mobile and even consoles. The aim of this series is not just to teach you the code, but to give you a solid understanding of the object-oriented programming paradigm (covered later in the series).

To get started, you’ll need a programming environment to code in. There are different programs you can use for writing C# code and testing your applications such as

In these tutorials, I will be demonstrating C# coding using Xamarin on MacOS although the steps will be mostly the same using other software on other platforms.

Watch the video below and then scroll down to see the sample code for your first Hello World application in C#.

Sample code

using System;

namespace MyCSharpProject
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            // This displays "Hello world" message:
            Console.WriteLine("Hello world!");
            // This stops console from auto-exiting:
            Console.ReadLine();
        }
    }
}

Next tutorial: Variables, constants and data types

Making the player jump in a 2D game with Unity and C# code

WARNING: If you found this page linked from a paid course on Udemy, you have been ripped off. This course is available as a free video tutorial series here and on my YouTube channel. If you have paid for these tutorials, contact Udemy for a refund and report the course to Udemy. I created this course with the intention of it being available to anyone for free.

In this tutorial you will learn how to write a script to make your player jump in a 2D game with C# code in Unity. In the following tutorial, you will learn how to make the player jump only when they are touching the ground.

Watch the video below and scroll down to view the sample code.

Sample code

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

  public float speed = 5f;
  public float jumpSpeed = 8f;
  private float movement = 0f;
  private Rigidbody2D rigidBody;

  // Use this for initialization
  void Start () {
    rigidBody = GetComponent<Rigidbody2D> ();
  }
  
  // Update is called once per frame
  void Update () {
    movement = Input.GetAxis ("Horizontal");
    if (movement > 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    }
    else if (movement < 0f) {
      rigidBody.velocity = new Vector2 (movement * speed, rigidBody.velocity.y);
    } 
    else {
      rigidBody.velocity = new Vector2 (0,rigidBody.velocity.y);
    }

    if(Input.GetButtonDown ("Jump")){
      rigidBody.velocity = new Vector2(rigidBody.velocity.x,jumpSpeed);
    }
  }
}

Next tutorial:  Jumping with ground check

Creating a List app for iOS with Xamarin

In this tutorial, we will look at how to create a list app for iOS. The example used in this tutorial will be a list of cities. When the name of a city in the list is tapped by the user, details about that city will be presented (we will achieve that part in the next tutorial).

image1
The iOS list app.

Step 1

Begin by clicking File > New Solution in Xamarin Studio and then select iOS App and Single View App. Then click Next.

image2

Step 2

Give the app a name (the app in this example will be called ListAppIOS), select the target iOS version and then click Next.

image3

Step 3

Confirm the project name, solution name, project location and click Create.

image4

Step 4

Open the Main.storyboard file and select an iPhone model from the View As drop-down list (eg. iPhone 6).  Then drag a Table View Controller on to the storyboard next to the main screen.

image5

Step 5

Now right-click on the main screen (on the left) and select Delete to remove this screen as it is no longer needed (you may need to click Delete twice). The Table View controller will now be the first screen that loads when the app launches.

image6

Step 6

Now that the first screen is deleted, the ViewController.cs file will no longer be needed so we can delete it. Select the ViewController.cs file, right-click it and select Remove.

image7

Then select Delete when the dialog box appears asking you.

image8

Step 7

Now you will need a class that will control the table view controller. Select the Table View Controller by clicking on the bar at the bottom of it. You should see the Class property on the Properties panel. At the moment it is empty but it needs a class so we can create the class here.

image9

Click in the Class property field and type in a name for the new class eg. CitiesViewController. Then press Enter. You’ll notice a new C Sharp (.cs) file is created for this new class and it will appear in the solution panel.

image10

At this stage, if you simulate the app you will see an empty list on the main screen as shown below.

image11

Step 8

Now go back to the Main.storyboard file and click on the title bar at the top of the app screen. We need to add a reuse identifier that allows the app to re-use rows on the table on the app screen as the user scrolls down the screen rather than having to generate new rows. Change the Identifier value to City.

image12

Step 9

Now open the CitiesViewController.cs file so that you can start populating a list of cities in the table view controller. Adding the using System.Collections.Generic; line allows us to use the List class that can contain many elements. Before we start creating a list of cities we need to define what a city is by creating a City class and giving it some properties such as its name (string), the country and state it belongs to (strings) and its population (integer).

image13

Step 10

Once we have created the class City, we can create a List that will contain many elements and set its type to City so that every time added to the list will be a city. First we give the list its name and set its type, and then we can create the list.

image14

Step 11

Now that we have create the list, we can populate the table view with data from the list.

image15

Step 12

Now we need to override a few of methods: NumberofSections, RowsInSection, and GetCell. For each method, as you type public override and press the spacebar key, you will be presented with methods that you can select from. Start typing the name of the method you want to override and then double-click it to add the override method.

The first method we override is NumberofSections which can be set to return 1 because only one section is needed in the table. As shown below on line 36, we set return to 1.

The second method is RowsInList which is set to return CityList.Count; (this will make as many rows in the table as there are cities in the list) as seen on line 41.

The third method we override is GetCell which is the method that will allows us to get a re-usable cell, modify its values, and return it to the table view. We create a variable called cell and we use the name of the reuse identifier we set for the table view controller back in Step 8 (line 46). We also create a variable called data which set each row to contain data from the city list (line 47) and we set the text on the TextLabel (a default TextLabel already exists) for the cell to be the name of the city for that row (line 48). Lastly, we return cell (line 49).

Here are the three methods once they have been added.

image16
Click the image to see a larger version.

Step 13

At this stage, if you test the app in the simulator you will see the list with the name of each city on each row of the list (we only have two rows in this list but you can add many more to your list).

image17

Now we need to customised the rows in the list to improve their appearance and so they can display some more information about each city.

Step 14

Now we will add more details to each row in the table view (the state and country). Open the Main.storyboard file and click once on the row at the top of the table view. Go to the Class field. We will create a class that will represent the row.

image18

The Class field should currently say UITableViewCell (if it says UITableView, then you may have clicked twice on the row on the screen. De-select the row, then click it once making sure that that the Class field says CityTableViewCell. Type in CityTableViewCell in the Class field and press the Enter key on the keyboard.

image19

You should now see the CityTableViewCell.cs file in the solution panel. Double-click it to open the file – we will now start adding code to this new C Sharp file.

image20

Step 15

Now we need to create a local private variable called City just for this class. Then we need to create a global variable for this data so it can be accessed anywhere. In this, we will have a getter which will get the method that we will access the value of the property (it will return bookData – the private property). Then we set the bookData to the value we are getting.

image21

Go back to the Main.storyboard file. Drag a Label element on to the row at the top of the screen.

image22

Resize the row at the top of the screen because it will need to fit more labels by dragging it down from the circle at the bottom of the row.

image23

Step 16

Now add more Label elements to the screen to display the city name, state name, country name, and population. Arrange and resize the labels so they will be able to fit their text in. Give each label a default property for Text so that you know what each label represents. You can also change the colours or font style. For example, the city name label below is set to Size 19pt Semibold.

Change the Name property for each Label. The labels on this screen have the following names:

  • cityNameLabel (this will display the city name)
  • stateCountryLabel (this will display the state and country separated by a comma)
  • populationLabel (this will display the city’s population)

image24

Step 17

Go back to the CityTableViewCell.cs file. We now need to access the labels from the screen that we created in Step 16 and set the text on the labels to match the properties from cityData when the the cityData property receives its value. Add the lines of code below and then save the file.

Note that the state and country are added together with a comma and space in between them. Also note the #,##0 inside the ToString() brackets – this will place commas between the hundreds and thousands for population when displayed on the populationLabel to improve formatting.

image25
Click the image to see a larger version.

Step 18

Go back to the CitiesViewController.cs file. Instead of simply getting a cell, we will now get a cell as CityTableViewCell so we need to add the extra code to the GetCell method as highlighted on line 46 of the code below.

image26
Click the image to see a larger version.

We also need to change the code so that instead of having cell.TextLabel.Text = data.Name; we will now just have cell.cityData = data;

image27
Click the image to see a larger version.

This means we are no longer accessing a property of the data but instead we are just passing the city. Now it is time to test the app. When you test your app in the simulator you may notice some problems with the formatting of your rows such as the row height or overlapping text as seen below. We will look at how to fix this in the next step.

image28

Step 19

After testing, you may realise that you need to change the font size for labels, label width/height, or placement of labels. You may also see overlapping text or items that appear to be in the wrong row. If you see this, you may need to adjust the row height. Click on the Table View (not the row) and then click on the Layout tab on the Properties panel. Under Table View Size, change the Row Height value to something more suitable and test your app. Keep adjusting the value and testing as needed. In this example app, the Row Height value has been changed to 115.

image29

That’s it! Now you can go and test your app! If you want to add a detail screen for each item in the list, then check out the next tutorial.

Adding more screens to an iOS app

This tutorial explains how to add more than one screen to your iOS app and link screens together using buttons. We will use a simple example for this tutorial as show below…

iosmultiscreenapp

Watch the video below or scroll down to read the step-by-step instructions and sample code.

Video

Step 1

Start by creating a new solution (click File > New Solution).

ims1

Step 2

Give your app a name, select a minimum supported iOS version and click Next.

ims2a

Confirm the project and solution names, the project folder location and click Create.

ims2b

Step 3 

Open the Main.storyboard file and drag a Button element on to the screen. Give it a name and change its text value.

ims3

Step 4

Drag a Navigation Controller anywhere onto the storyboard. It should look like this…

ims4

Step 5

Right-click the Root View Controller and click Delete.

ims5

Step 6

Hold down the Ctrl (Control) key while dragging the Navigation Controller screen to your main screen (you will see a blue line linking the two screens together). The select Root from the list of options – this will make the main screen the root screen (the screen that loads first when the app starts running).

ims6

Step 7

Now drag a View Controller element onto the storyboard and place it to the right side of your main (root) screen. This will create a new screen which will be the second screen in your app.

ims7

Step 8

Hold down the Ctrl (Control) key while clicking and dragging the button on the main screen to the second screen. When you see the list of options appear, select Appear.

ims8

Step 9

Now we can add a Button to get from the second screen back to the main screen. Drag a button element on to the second screen. Give it a name. When you name the first element that you add to a new screen, you will see a yellow warning icon. Click it and then you will need to type in the name of the new ViewController for this screen  (for example, ScreenTwoViewController)– the name you provide will be the name of a new C# file that will contain the code for this screen. Change the Title property of the button the Back.

ims9

Step 10

Now click on the new button on the second screen. Hold down the Ctrl (Control) key while dragging this button to the main screen. Click on Show. This will make the Back button take the user back to the main screen when they tap it.

ims10

Lastly, double-click on the main screen’s title so you can rename it.

ims11

That’s it! Now you can test out your app.

Send SMS from Android app with Xamarin

In this tutorial you will learn how to make an Android app that can send SMS messages. Firstly, we will create a button that can send a pre-determined message to a pre-determined number. We will then extend the app by adding text fields where the user can enter a number and their message.

This is what the app will look like at the end of this tutorial…

smsapp

Step 1

To get started, open Xamarin and click File > New and select Android App from the list of templates. We will be writing this app in the C# language.

sms1

Step 2

Give your app a name. In this example, the app is called SMSApp and Modern Development has been selected as the Target Platform.

sms2

Step 3

Confirm the project and solution name as well as the folder the project will be stored in. Then click on Create.

sms3

Step 4

Open the Main.axml file in the Resources > Layout folder and delete the ‘Hello world, click me!’ button.

sms4

Step 5

Drag a new Button element from the Toolbox on to the screen. Rename its Id to @+id/sendButton and change the Text value to Send SMS.

sms5

Step 6

Now open the MainActivity.cs file to add the code. Delete the code that is highlighted below.

sms6

Step 7 

Click on the Project menu and then select the Project Options (it will be the name of your app project – here it is called SMSApp Options).

sms7

Step 8

Select Android Application from the list and then in the Required Permissions list, check the SendSms option and click on OK. This will allow the app to send SMS messages.

sms8

Step 9

Add the using Android.Telephony; line to the top section of the code.

sms9

Step 10

Define the sendButton as a Button element in your code.

sms10

Step 11

Add the following highlighted line of code to the OnCreate method so that you can access the button element from the screen.

sms11

Step 12

Now create a button click event. Type in sendButton.Click+= then press the spacebar. Double-click the option to create the SendButton_Click method.

sms12

Step 13

Inside the SendButton_Click method, add the following highlighted code.

sms13

There are two values that you need to change. The phone number (shown as 0123456789 above) needs to be changed and also the SMS message contents (shown as Hello world above). Change these values as you like. You can also get values from existing variables here or from user input in text fields. Now go and test your app on a phone with a working SIM card.

Adding user input

Now we will allow the user to enter in a number and a message to send. We will need to add a couple of text labels and text fields to the screen.

Step 14

Open the Main.axml file. Add two Text (Medium) elements and two Plain Text elements as shown below. The Text (Medium) elements should ask the user to enter a number and enter a message.

sms14

Step 15

Rename the first Plain Text element (under Enter a number) to @+id/numberEditText. Rename the second Plain Text element (under Enter a message) to @+id/messageEditText.

sms15a

sms15b

Step 16

Go back to the MainActivity.cs code. Modify the code by adding the highlighted lines of code shown below. You firstly need to define the EditText elements in the MainActivity class (lines 11-12) and then allow the code to access these elements from the screen (lines 22-23). Then you need to modify the SendButton_Click method so that the text entered by the user (the phone number and the desired message) are saved in string variables (lines 31-32). These variables are then used in line 33.

sms16

That’s it! Now go and test your completed app.

Improving the Android Temperature Converter App

In this tutorial we will look at how to improve the code in the Temperature Converter App for Android from the previous tutorial. If you have tested the app yourself, you might notice that the app works great when the user enters only numbers. However, what happens when a user enters nothing at all? The app will crash!

We will look at how to prevent such errors from occurring so that the app won’t crash if the user accidentally (or deliberately) enters non-numeric values or nothing at all – this is something known as data validation. This is what the app will look like…

Android Temperature Converter app (with data validation)
Android Temperature Converter app (with data validation)

The code below is from the same app but has some new code added to it. All of the code is commented, explaining what each new line does. None of the design elements (buttons, labels, text fields) have been changed in any way.

using Android.App;
using Android.Widget;
using Android.OS;
// need to add using System; to access the Math functions
using System;

namespace TemperatureConverter
{
  [Activity (Label = "TemperatureConverter", MainLauncher = true, Icon = "@mipmap/icon")]
  public class MainActivity : Activity
  {
    Button cButton;
    Button fButton;
    TextView resultTextView;
    EditText temperatureTextEdit;

    protected override void OnCreate (Bundle savedInstanceState)
    {
      base.OnCreate (savedInstanceState);

      // Set our view from the "main" layout resource
      SetContentView (Resource.Layout.Main);

      cButton = FindViewById<Button> (TemperatureConverter.Resource.Id.cButton);
      fButton = FindViewById<Button> (TemperatureConverter.Resource.Id.fButton);
      resultTextView = FindViewById<TextView> (TemperatureConverter.Resource.Id.resultTextView);
      temperatureTextEdit = FindViewById<EditText> (TemperatureConverter.Resource.Id.temperatureTextEdit);

      cButton.Click += CButton_Click;
      fButton.Click += FButton_Click;
    }

    void FButton_Click (object sender, System.EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = temperatureTextEdit.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse (tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create fResult variable which stores result of C to F conversion
          float fResult = temp * 1.8f + 32f;
          // Change fResult to decimal data type and round to 2 decimal places
          decimal fResultRounded = Math.Round ((decimal)fResult, 2);
          // Display result on the screen
          resultTextView.Text = fResultRounded.ToString () + " degrees Fahrenheit";
        }
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultTextView.Text = "Enter numbers only";
        }
        // If nothing was entered by user, ask user to enter a number
      }
      else {
        resultTextView.Text = "Enter a number to convert";
      }
    }

    void CButton_Click (object sender, System.EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = temperatureTextEdit.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse(tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create cResult variable which stores result of F to C conversion
          float cResult = (temp - 32f) / 1.8f;
          // Change cResult to decimal data type and round to 2 decimal places
          decimal cResultRounded = Math.Round((decimal)cResult, 2);
          // Display result on the screen
          resultTextView.Text = cResultRounded.ToString () + " degrees Celsius";
        } 
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultTextView.Text = "Enter numbers only";
        }
      }
      // If nothing was entered by user, ask user to enter a number
      else {
        resultTextView.Text = "Enter a number to convert";
      }
    }
  }
}

Making a Cookie Clicker game for iOS

In this tutorial we will make a Cookie Clicker game for iOS mobile devices using Xamarin.We made the same app for Android in a previous tutorial and now we are going to make it for iOS devices. You will also learn how to use images for buttons instead of plain text.

This is what the basic working app will look like but you can improve the look of it by change the text and background colours and by adding more options.

iOS Cookie Clicker app
iOS Cookie Clicker app

Watch the video below or scroll down for the full instructions and sample code.

Video

Step 1

Start a new Solution (File > New > Solution). Select App under iOS and then select Single View App. Click on Next.

ioscc1

Step 2

Give your app a name, select the minimum iOS version you want to support and click Next.

ioscc2

Step 3

Give your project and solution a name (you can keep it as the default) and then choose the location where you will store your project (eg. the Projects folder). Then click on Create.

ioscc3

Step 4

Open the Main.storyboard file (in the Resources directory). Change the view from Generic to the iPhone model you are targeting (eg. iPhone 6S).

ioscc4

Step 5

Drag a Button element on to the screen from the Toolbox.

ioscc5

Step 6

You will need a cookie image for your app. Once you have an image on your computer, select the Resources folder. Click the cog icon, then Add > Add Files from Folder.

ioscc6

Step 7

Find the folder that contains your cookie image. Then click on Open.

ioscc7

Step 8

Click the checkbox next to the image you want to use and then click OK.

ioscc8

Step 9

Choose Copy the file to the directory and then click OK.

ioscc9a

You should now see the image in the Resources directory.

ioscc9b

Step 10

Now select the Button you added earlier and from the Widget tab on the Properties panel, scroll down until you see the Background property. Click the dropdown box and choose the image you want to use (eg. cookie.png). Alternatively, type in the filename in the text box.

ioscc10

Now you have a cookie image as the background for your button. However, the button is very small so it will need resizing.

ioscc10b

Step 11

Click and drag the corners of the button to enlarge it so that the background image of the cookie is nice and clear.

ioscc11

Step 12

Now go and remove the Default title value under Title on the Properties panel so that the button text is no longer visible on the button.

ioscc12

Step 13

Add a Label element to the screen under your cookie button and change its Text value to say ‘0 clicks’.

ioscc13

Step 14

Change the Name of the Button element to cookieButton.

ioscc14

Step 15

Change the Name of the Label element to clicksLabel.

ioscc15

Step 16

Now all that remains is adding the code that will count and display the number of clicks. Open the ViewController.cs file to begin coding.

ioscc16

Step 17

Firstly, create a variable called clicks that will contain an integer value. Its initial value should be 0 before any clicks have been recorded. Inside the public partial class ViewController : UIViewController section, add the following line of code:

int clicks = 0;

ioscc17

Step 18

Now you need to add a button touch event so that every time the cookie button is touched, the clicks variable’s value will increase by 1. To do this, go to the ViewDidLoad method and make some new space under the base.ViewDidLoad() line. Start typing cookieButton.TouchUpInside+= and then press the Spacebar. As you do this, you will see a list of options. Double click the CookieButton_TouchUpInside option to create a new method.

ioscc18

After creating the new CookieButton_TouchUpInside method, you can now add code inside the method that will run when the cookie button is touched by the user. This code should increase the clicks variable by 1 and display the number of clicks every time the button is touched.

ioscc18b

Step 19

Add the following code inside the CookieButton_TouchUpInside method:

clicks++;
clicksLabel.Text = clicks.ToString() + “ clicks!”;

This code will increase the clicks variable by 1 every time the button is tapped as well as displaying the value of the variable and concatenating (joining) the value to the text ‘ clicks!’ – for example 20 clicks! Note that the clicks variable’s value has to be converted to a string before it can be displayed on the button.

ioscc19

Now you can test the app!

ioscc19b

When you test the app, click or touch the cookie button and you should see the number of clicks displayed increased, as shown below.

iOS Cookie Clicker app
iOS Cookie Clicker app

Try extending the app by adding some buttons with the options to ‘buy’ items or unlock items after a certain number of clicks. You could also use a timer to increase the number of clicks automatically over a period of time (eg. 5 clicks every second). You might also like to change the colour of the text and the background of the app.

Sample C# code

Here is the sample C# code for the ViewController.cs file (please note that the namespace should match the project/solution/app name of your app. It is called CookieClickerIOS in this example.

using System;

using UIKit;

namespace CookieClickerIOS
{
  public partial class ViewController : UIViewController
  {
    int clicks = 0;

    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
      base.ViewDidLoad ();
      // Perform any additional setup after loading the view, typically from a nib.

      cookieButton.TouchUpInside+= CookieButton_TouchUpInside;

    }

    void CookieButton_TouchUpInside (object sender, EventArgs e)
    {
      clicks++;
      clicksLabel.Text = clicks.ToString () + " clicks!";
    }

    public override void DidReceiveMemoryWarning ()
    {
      base.DidReceiveMemoryWarning ();
      // Release any cached data, images, etc that aren't in use.
    }
  }
}