C# Code Reference for Xamarin

This page provides examples of C# syntax and some basic sample code to help you get started with C# programming using the Xamarin platform. This resource will also help you if you forget the syntax to common operations or statements in the C# programming language.

If you have any questions or any problems while using Xamarin or programming in C#, make sure you check out the Xamarin FAQ and Tips page.

Table of contents

C# Data Types

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 can hold larger size numbers than floats.
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”.

Basic code template

When you create a new file for a namespace in a solution in the Xamarin Studio application, it will usually look like the code shown below. In the code below, we can see it is within the namespace called MyCSharpApp and the name of this file is myFile.cs (where .cs stands for C-Sharp).

using System;
 
namespace MyCSharpApp
{
  public class myFile
  {
      public myFile ()
      {
        // code goes here
      }
  }
}

This code is made up of four sections:

  • The using section
  • The namespace
  • The class declaration section
  • The class contents

The using section

The section of the code lists the libraries that the file will be using (usually using System; is there by default). Quite often you will need to add more libraries you’ll need to use to this part of the code.

Namespaces

Namespaces are used a lot in C# and are used to organise the many classes you may have. Namespaces make it easy to keep a set of class names separate from another set of class names. The class names that are declared in one namespace will not conflict with the same class names that are declared in another namespace.

When you create a new solution in Xamarin, the namespace on your code will usually be the same name as the actual solution.

The class declaration section

All scripts contain a class that is named after the actual script. For example, if the script file is called calculator.cs then the class will be called calculator. Note that script file names and class names should not contain any spaces. The first line of this section (the class declaration) doesn’t really get changed much so it should usually be left alone unless there is a specific reason to change it. All of the code that exists between the opening { and closing } brackets is a part of this class. All of your code will go between these opening and closing brackets.

The class contents

The code placed in between the opening and closing brackets of the class is what makes up the script. All of your code goes here. A class may contain many methods. For example, a calculator script may contain a method that gets number input, another method that adds numbers together, another method that multiplies numbers, and so on.

Note that statements in C# have a semi-colon (;) at the end of the line. Leaving the semi-colon out can cause errors!

Comments

The // characters 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 an can help others understand the algorithm.

Here is an example of a comment:

// This is a comment

Variables

To create a variable it must firstly be given a name and a type. Variable declaration uses the following syntax:

<variable type> <variable name>;

Variables should be given meaningful names. Variable names should never contain spaces. To declare a variable that is of the integer data type and is called myNumber, you would write the following:

int myNumber;

You can also assign a value to a variable during its declaration like this.

int myNumber = 5;

Or you can assign a value on another line after the variable has been declared like this:

myNumber = 5;

To declare a string variable, you would write something like this:

string message;

And you can also assign the value during declaration like this:

string message = "Hello World";

These are just a few examples of how to create variables in C#. Remember that strings are contained inside double quotes and chars are contained inside single quotes. Integers, floats, doubles, and boolean values are not placed inside quotes.

Variable scope

The scope of a variable dictates where it can be used. As mentioned earlier, classes and methods use opening and closing brackets and everything inside those brackets is called a ‘block’.

Variables can only be used within the block that they were created in. If a variable is created inside a class, it can only be used inside that class. If a variable is created inside a method (or function), it can only be used inside that method. For example, if you create a variable inside a getNumbers method, it can’t be used inside the addNumbers method because they are two different blocks.

However, if a variable is created in a class but outside of all of the methods on that class, it will be available in all of the methods in that class because those methods are in the same ‘block’ that the variable is in. Also, if a variable is a public variable or created in a public method, then it can be accessed and used in other methods (read more below).

Public and private

In code, you might see the keywords public or private. These are known as access modifiers. Private variables can only be used inside the file that they were created in. This means that other scripts or code editors cannot see or modify these variables.

However, public variables are visible to other scripts or methods. To make a public or private variable or method, just add the private or public keyword before the variable type and name during declaration, for example (to make a public variable):

public int myNumber;

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

You will see how these operators can be used for conditional statements after reading further on.

Arithmetic operators

Arithmetic operators are used for performing standard math operations on variables and are usually only used number variables (although they can be used for other things too).

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;

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.

Equality operators

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 equality 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.

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.

Conditional statements

Conditional statements are used so that your program can make decisions. When your program has a range of conditions, you can build powerful algorithms. A basic conditional statement is the if statement.

if statements

The most basic type of conditional statement is the if statement. The if statement basically works like this: if something is true, then do this. The basic syntax looks like this:

if( <condition>)
{
// do something
}

The condition goes inside the ( and ) brackets. The action that will occur (if the condition evaluates to true) goes inside the { and } brackets. For example, to say the message “Hello World” only if the value of x is greater than 10, you would use the following code:

if(x>10)
{
 Console.WriteLine("Hello World");
}

In the code above, the condition is to check whether x is greater than 10. As an example, if the value of x was 11, then the message “Hello world” would be displayed. If the value of x was 9, then nothing would happen. If the value x was exactly 10, nothing would happen because the value of x needs to be greater than 10 for the message to be displayed.

if/else statement

Regular if statements are easy to use. However, they don’t specify what the program should do if the condition evaluates to false. if/else statements allow you to specify what action will occur when a condition evaluates to true and also what will occur if the condition evaluates to false. This is known as a binary selection structure.

The if/else statement basically reads as “if something is true, then do this, otherwise do this other thing”. The syntax looks like this:

if(<condition>)
{
// do something
}

else
{
// do something else
}

Here is an example of a basic if/else statement that will display a message based on someone’s age stored in an ‘age’ variable.

if(age>=18)
{
 Console.WriteLine("You are old enough to vote");
}
else
{
 Console.WriteLine("You are not old enough to vote");
}

if/else if statement

The limitation of the if/else statement is that it only allows two possible paths. What if you want your program to be able to go down many different paths? What if you have many different conditions you want to check? That is where the if/else if statement comes in.

The if/else if statement provides more options than the if/else statement. It is set up in the same way but it has more than one condition. The else part is optional in an if/else if statement.

Here is some sample code for the if/else if statement:

if(age>=18)
{
 Console.WriteLine("You are old enough to vote");
}
else if(age==17)
{
 Console.WriteLine("You can vote after your next birthday");
}
else
{
 Console.Writeline("You are not old enough to vote");
}

Loops (iteration)

There are two main types of loops you can use in C# to repeat sections of code. These are called the while loop and for loop.

while loop

The while loop is the easiest type of loop to use for repetition of code. The basic syntax is as follows:

while(<condition>)
{
// do something
}

It looks very similar to an if statement. However, an if statement only runs the code it contains once. A while loop will run the code that it contains over and over again until the specified condition evaluates to false. Any code inside the { and } brackets will run inside the loop.

Here is an example of a while loop in the C# language:

int count = 0;
 
while(count <10)
{
 count++;
 Console.WriteLine(count);
}

In the example above, the count variable is initially set to 0. The loop will check if the count variable is less than 10. If it is not less than 10, it will add 1 to the count variable and then display the variable’s value. This will keep repeating until the condition evaluates to false when the count variable’s value is no longer less than 10. When this occurs, the loop will end.

It is important that a condition be specified that will allow the loop to end, otherwise the loop will never end! This is known as an infinite loop.

for loop

The for loop is a little more complex than the while loop but at its simplest level it is very easy to set up. The syntax looks like this:

for(<initialise counter>;<condition>;<increment the counter>)
{
// do something
}

Semi-colons separate three important components of the for loop inside the ( and ) brackets. The first part is where a counter is initialised, for example int i=0. The second part is where the condition is specified, for example i<10. The third part is how much to increment the counter by each time the loop runs (each iteration), for example i++ would increment the counter by 1.

for loops are great for using as counters to repeat a section of code a certain amount of times. They are also great for repeating operations on each item in an array (looping through an array) or each character in a string. Below is an example of a for loop.

for(int i=0; i <10; i++)
{
 Console.WriteLine(i);
 // the value of i will be displayed for each iteration of the loop
}

Methods

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).

Examples of suitable method names include calculateScore, addNumbers, multiplyNumbers, getUserDetails, etc.

Creating methods

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

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 n1 and n2. 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 will be returned as a float.

public static float addNums(float n1, float n2)
 {
   float answer = n1 + n2;
   return answer;
 }

The method above will add two numbers together (the two parameters n1 and n2) 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 myMethod, you would write:

myMethod();

If the method contained a parameter (eg. the value 10), it would be called like this:

myMethod(10);

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

int x = 10;
myMethod(x);

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 myMethod() in the example code above returns a value, then it should be stored in a variable, for example:

int result = myMethod(x);