Basic Data Types and Methods in C#

In this post I will cover basic data types and methods in C# with examples.

Basic data types

char MyChar = ‘c’; // Just one character
String MyString = “hello there”; // Several characters
int MyInt = 15; // Integer
double MyDouble = 1.23; // Decimal
Boolean MyBool = true; // true or false

List

// A list of strings, containing the elements “apple” and “orange”
List ListOfStrings = new List(new String[] { “apple”, “orange” });

// Looping throught ListOfString (starting with index 0 and ending with index Length – 1) and printing all its elements
foreach (String s in ListOfStrings)
{
Console.WriteLine(s);
}

Dictionary

// A dictionary is a collection of key-value pairs. This dictionary has keys of type int
// and values of type string. Key 1 corresponds to value “potato”, and key 2 to “carrot”.

Dictionary MyDictionary = new Dictionary()
{
{ 1, “potato” },
{ 2 , “carrot” }
};

//This dictionary has both keys and values of type string. Key “first” has value “table”
// and key “second” has value “chair”

public static Dictionary MyStringDictionary = new Dictionary()
{
{ “first”, “table” },
{ “second” , “chair” }
};

// Printing all the values in the dictionnary MyDictionary
foreach (String item in MyDictionary.Values)
{
Console.WriteLine(item);
}

Basic Methods With Examples

If Else condition

int a = 1;
int b = 2;
int c = 3;
if( a == b )
{
Console.WriteLine("a equals b");
}
else if( a != c )
{
Console.WriteLine("a does not equal c");
}
else
{
Console.WriteLine("nothing above matched");
}

Do While loop

When using the do-while loop, the code will always go through the loop at least once. At the end, it will asses if it should re-enter or exit the loop. We should make sure not to create an endless loop. In this example, i starts at 0 and is augmented by 1 each loop. The loop will only be re-entered while i is less than 10.

int i = 0;
do

{
Console.WriteLine(i);
i++;
}
while (i < 10);

While loop

The while loop assesses its condition before entering to loop. Contrary to the do-while loop, depending on the condition, it is possible the while-loop is never entered.

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

For loop

In the for loop, the iterator and it’s conditions are given directly inside the parenthesis. In this example, the iterator i starts at 0 and augments by 1 each run. The loop will only be run as long as i is less than 10.

for (int i = 0; i < 10; i++)
{
Console.WriteLine(i);
}

For each loop

The for-each loop is practical for going through a list of items. In this example we print all the elements in the list ListOfStrings, which is defined above.

foreach (String s in ListOfStrings)
{
Console.WriteLine(s);
}

Switch

Switch is used when we want to apply different behaviour depending on the value of the selector. It is important to add a break at the end of a case, otherwise the code will continue running the next case as well. Of course we can sometimes omit the break, if that is actually what we want to happen.

String select = "2";
switch (select)
{
case "1":
Console.WriteLine("case 1");
break;
case "2":
Console.WriteLine("case 2");
break;
case "3":
Console.WriteLine("case 3");
break;
default:
Console.WriteLine("none of the ebove matched");
break;
}

Try – Catch

Try-catch can be used to catch exceptions, in case we want to treat them ourselfs, or even if we just want to ignore them. We can catch all exceptions, or just specific exceptions, for example DivideByZeroException as shown in the commented code below.

int a = 0;
try
{
int divedyByZero = 10 / a;
}
catch(Exception ex) // Catch all exceptions
//catch(DivideByZeroException ex) // Catch specifically only DivideByZeroException
{
Console.WriteLine("Catched Exception: " + ex);
}
Console.WriteLine("Still running OK"); // Without try-catch would have stopped run on error (divide by zero)

Getting started with C# and Visual Studio

C# is an object-oriented programming language developed by Microsoft. To get started, we need to install an IDE, usually Microsoft Visual Studio.

Download Visual Studio and start installation. Select “Universal Windows Platform Development”.

Generally we can just leave the default packages (no optional packaged needed for now).

We can now start the installation process, which can take quite a long time. When the process is finished, the computer needs to be restarted before we can start using Visual Studio.

After restarting the computer, we can open Visual Studio. It will ask you to either sign in (if you already have a Microsoft account), or to create an account.

Next we will be prompted to select development settings and a theme. We can select “General” for development settings. As for the theme, it’s a matter of personal taste.

To create a new project, select File > New > Project.

In the pop-up, select “Console App (.NET Core)”. Name and save the project.

To add a new class to the project, select Project > Add class (C# Class).

To build code in Visual Studio, select Build > Build solution.

To run the project, select Debug > Start Without Debugging.

Locating web elements using XPath

XPath can be used to locate web elements on a web site. We should construct unique XPaths, meaning only one element can be found on the page using the XPath we have constructed. In Firefox and Chrome, we can right click on the element on the screen and select “Inspect Element”. This will open the browser’s developer tools window on the Inspector-tab. There we can see the HTML of the page, with the part corresponding to the element as highlighted. We can construct a unique XPath based on that snippet.

If the website has unique ids for the web elements, they are often a good choise for constructing the XPath. For example, consider the following element:

<button id="loginButton" class="LoginDropdownButton">Login</button>

We could construct the XPath using id, class and/or text. If the id seems to be unique, it would be a good choise. But sometimes elements do not have ids defined, or they are dynamic, in which case other attributes or a mixture of them can be used.

XPath Examples

Basic XPath syntax to find an element of type input with id lastName:

//input[@id=”lastName”]

Numeric selector : If several web elements corresponding to the criteria are found on the page, you can select the first one by adding [1] at the end. Similarly, by adding [2] we would select the second one, and so on.

(//input[@id=”lastName”])[1]

Following sibling : Select the following sibling of type div of an element of type div containing the text First name:

//div[contains(text(), “First name”)]/following-sibling::div

Contains text : find element of type a which contains text my name in its text part:

//a[contains(text(), “my name”)]

Contains – several search criteria : find an element of type a which has href which contains myLink and text which contains my name:

//a[contains(@href, “myLink”)][contains(text(), “my name”)]

Any type and partial id : find element of any type (*) whose id contains thisId:

//*[contains(@id, “thisId”)]

Trying out an XPath on the browser

Before using the xpath in our code, we can try it out on the browser. In Firefox and Chrome, this can be done by typing F12 and selecting the Console-tab. Then we can try the path with the following syntax:

$x(‘path’)

After clicking Enter, we should get an array as a response. We want to find the element on the page exactly once, which means we should have an array with one element. We can hover on the array, and the element will be highlighted on the page. If the array has no elements, it means something went wrong with the XPath, as no corresponding elements are found. If the array has several elements, we can try to add more details to the description. If that is not possible, we can use the numeric selector as described above.

Defining locators

We can use XPath to define locators in Selenium page objects:

public static final String LAST_NAME = "//input[@id=\"lastName\"]";