Tag Archives: csharp

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#

Switch statements in C#

This tutorial explains how to write switch statements in C# language. Switch statements are used to select one from many different blocks of code. A switch statement can take a variable and check if its value matches one of many different specified values. Once the switch statement finds a matching case, it will run the code inside that case and the stop testing all the other cases.

Watch the video below and then scroll down to the sample code to see how switch statements work.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int myNumber = 5;
      switch (myNumber) {
        case 1:
          Console.WriteLine("The number is 1");
          break;
        case 2:
          Console.WriteLine("The number is 2");
          break;
        case 3:
          Console.WriteLine("The number is 3");
          break;
        default:
          Console.WriteLine("I don't know this number");
          break;
      }
    }
  }
}

Next tutorial: While loops in C#

Making comparisons in C# (if, else if, and else statements)

In this tutorial you will learn how to make comparisons in C# using the following conditional statements:

  • if
  • else if
  • else

We can check, for example, if a number is less than, greater than, less than or equal to, greater than or equal to, equal to, or not equal to another number. We can also check if a string variable is equal to another string value (for example, checking if a password is correct). To make comparisons, we will need to be familiar with comparison operators.

Comparison operators

Comparison (or equality) operators are used to compare two values. The result of using an equality operator can either be true or false. The only type of variable that can store the result of an equality operator is a Boolean. The table below describes the comparison operators used in C#.

Operator Description
== This operator is used to check if two values are equal eg. x == 5 would return true if x had a value of 5.
> and < The ‘greater than’ and ‘less than’ operators are used to check if values are greater than or less than another value. For example, x > 5 (if the value of x was 3 than it would return false).
>= and <= The ‘greater than or equal to’ and ‘less than or equal to’ operators are similar to the ‘greater than’ and ‘less than’ operators. For examples, 5>=5 would return true because 5 is equal to 5, and 6<=10 would return true because 6 is less than 10.
!= The ‘not equal’ operator is used to check if two values are not the same as each other. For example, x != 10 would return true if the value of x was 9 because 9 is not equal to 10. However, y != 5 would return false if the value of y was 5.

Watch the video below which shows how to make comparisons using if, else if, and else statements (scroll down for the sample code).

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int x = 11;

      if (x > 10)
      {
        Console.WriteLine("x is greater than 10");
      }
      else if (x < 10)
      {
        Console.WriteLine("x is less than 10");
      }
      else{
        Console.WriteLine("x is equal to 10");
      }
    }
  }
}

Logical operators

We can also check if multiple conditions evaluate to true or if at least one of multiple conditions evaluate to true in a single if statement using logical operators. Logical operators are used for complex conditions. The table below describes each logical operator.

Operator Description
&& This is known as the AND operator and is used to check if both values are true in a complex condition.
|| The is known as the OR operator and is used to check if at least one of the values is true when two values are compared. It will return true if either one or both values are true.
! This is known as the NOT operator and will return the opposite of a Boolean value. For example !true; would return false and !false; would return true.

Here is an example of using the && logical operator to display a message only if a user’s first name is “Joe” AND their last name is also “Bloggs”.

if (firstName == "Joe" && lastName == "Bloggs")
{
   Console.WriteLine("Hello Joe Bloggs.");
}
else
{
   Console.WriteLine("I don't know you.");
}

Watch the video below to see how you can use logical operators in conditional statements and then scroll down for the sample code.

Sample code using logical OR operator

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string firstName = "Joe";
      string lastName = "Smith";

      if (firstName == "Joe" || lastName == "Bloggs")
      {
        Console.WriteLine("Hi Joe.");
      }
      else{
        Console.WriteLine("I don't know you.");
      }
    }
  }
}

Sample code using logical AND operator

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string firstName = "Joe";
      string lastName = "Bloggs";

      if (firstName == "Joe" && lastName == "Bloggs")
      {
        Console.WriteLine("Hi Joe.");
      }
      else{
        Console.WriteLine("I don't know you.");
      }
    }
  }
}

Next tutorial: Switch statements 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#

Combining types in output statements in C#

This tutorial shows you how you can combine types in a Console.WriteLine() output statement. For example, you can combine a string with an integer or float value. Watch the video below and scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string message = "The result is ";
      float num1 = 6f; // Assign value to num1 variable
      float num2 = 4f; // Assign value to num2 variable

      float result = num1 + num2 + 10f; // Add numbers

      result = num1 - num2; // Subtract
      result = num1 * num2; // Multiply
      result = num1 / num2; // Divide
      result = num1 % num2; // Mod

      int num3 = 30;
      num3--;

      Console.WriteLine(message + result); // String and float value combined in output statement
      Console.WriteLine(num3);
    }
  }
}

Next tutorial: Converting variable types in C#

Using comments in C#

Comments are useful for explaining the purpose of a piece of code or how it works. Comments can also be used to identify the author of code or when it was created or last updated.

In C# the // characters (two forward slashes) are used to add comments to your code. Any text on a line after the two forward slashes will not be treated as code. Comments are useful as they contain notes about what is happening in the code and can help others understand the algorithm. They won’t change the way a program runs and won’t be visible in the working program.

Here is an example of a comment:

// This is a comment

Watch the video below to see how to use comments and scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string message = "The result is ";
      float num1 = 6f; // Assign value to num1 variable
      float num2 = 4f; // Assign value to num2 variable

      float result = num1 + num2 + 10f; // Add numbers

      result = num1 - num2; // Subtract
      result = num1 * num2; // Multiply
      result = num1 / num2; // Divide
      result = num1 % num2; // Mod

      int num3 = 30;
      num3--;

      Console.WriteLine(result);
      Console.WriteLine(num3);
    }
  }
}

Next tutorial: Combining types in output statements

Arithmetic and assignment operators in C#

Operators

Operators are symbols that are used to perform operations on data. The range of different operations you can perform can usually be placed in these four categories:

  • Arithmetic operators
  • Assignment operators
  • Equality operators
  • Logical operators

In this tutorial we will look at arithmetic and assignment operators used in the C# language. Later on in these tutorials we will also look at equality and logical operators when we work with conditional statements.

Arithmetic operators

Arithmetic operators are used for performing standard math operations on variables and are usually only used on number variables eg. int and float (although they can be used for other things too eg. the  + operator can be used to join two strings together).

Operator Name / description
+ Addition – this operator is used to add two numbers together. It can also be used to concatenate (join) two strings together.
Subtraction – this operator is used to subtract one number from another.
* Multiplication – this operator is used to multiply two numbers together.
/ Division – this operator is used to divide one number by another.
% Modulus – this operator is used to divide one number by another but instead of returning the result, it returns the remainder of the division. Eg. 5%2 would return a result of 1.

Brackets can also be used for more complex math operations eg. 5 + (10 * (6 / 3) / 2);

The assignment operators follow standard mathematic order of operations. That means that the math works from left to right. Parenthesis are done first, multiplication and division comes second, and then addition and subtraction come third.

Assignment operators

Assignment operators are used to assign a value to a variable. The most frequently used assignment operator is the equals (=) sign. There are other operators as well that are used to combine multiple operations into one. The syntax of a standard variable assignment looks like this:

<variable name> <assignment operator> <value>;

For example: x = 5; (or int x = 5; if the variable’s type has not already been declared).

The table below shows the different assignment operators available in C#.

Operator Description
= The equals sign is used to assign the value on the right side of the equals sign to the variable on the left side of the equals sign.
+= , -= , *= and /= These assignment operators are also used to perform arithmetic operations and assign the result to the variable eg. x *= 5 is the same as saying x = x * 5.
++ and — These assignment operators are called increment and decrement operators and are used to increase or decrease the value of a variable by 5. For example, x++ is the same as saying x = x + 1.

Watch the video below to see how arithmetic and assignment operators are used in the C# language and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string message = "The result is ";
      float num1 = 6f;
      float num2 = 4f;

      float result = num1 + num2 + 10f;

      result = num1 - num2;
      result = num1 * num2;
      result = num1 / num2;
      result = num1 % num2;

      int num3 = 30;
      num3--;

      Console.WriteLine(result);
      Console.WriteLine(num3);
    }
  }
}

Next tutorial: Comments

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

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.