C# Basic Code Elements

Variables and different types.

C# is a static-typed language therefore we must define the variable type for the system to recognize it.

//Here is an example of the 6 kinds of variable types you can use
int anIntenger = 1;
float floatingNumber = 1f;
bool booleanValue = true;
string aString = "John";
char aSingleCharacter = 'a';
double usingDecimals = 1.75;
//Note, the float variable always has an f at the end of it.


using System;
public class Tutorial
{
   public static void Main()
   {
      string productName = "TV";
      int productYear = 2012;
      double productPrice = 279.99; 

      Console.WriteLine("productName: " + productName);
      Console.WriteLine("productYear: " + productYear);
      Console.WriteLine("productPrice: $" + productPrice);
   }
}

Examples of how arrays work in C#

using System;
public class Tutorial
{
   public static void Main()
   {
       string[] fruits = {"apple", "banana", "orange"};

      Console.WriteLine(fruits[0]);
      Console.WriteLine(fruits[1]);
      Console.WriteLine(fruits[2]);
   }
}

Using lists in C#

Here is a list where we added some prime numbers.

using System;
using System.Collections.Generic;

public class Hello
{
    public static void Main()
    {
        List<int> primeNumbers = new List<int>();
        primeNumbers.Add(2);
        primeNumbers.Add(3);
        primeNumbers.Add(5);
        primeNumbers.Add(7);
        primeNumbers.Add(11);

        Console.WriteLine(primeNumbers.Count);
        Console.WriteLine(primeNumbers[0]);
        Console.WriteLine(primeNumbers[1]);
        Console.WriteLine(primeNumbers[2]);
        Console.WriteLine(primeNumbers[3]);
        Console.WriteLine(primeNumbers[4]);
    }
}

Using the Dictionary list

Dictionaries are special lists, whereas every value in the list has a key which is also a variable.

using System;
using System.Collections.Generic;

public class Hello
{
    public static void Main()
    {
        Dictionary<string, int> inventory = new Dictionary<string, long>();
        inventory.Add("apple", 3);
        intentory.Add("orange", 5);
        inventory.Add("banana", 2);

        Console.WriteLine(inventory["apple"]);
        Console.WriteLine(inventory["orange"]);
        Console.WriteLine(inventory["banana"]);
        
        //Another example of using Dictionary for a phonebook
        Dictionary<string, long> phonebook = new Dictionary<string, long>();
		phonebook.Add("Alex", 415434543);
		phonebook["Jessica"] = 415984588;

		phonebook.Remove("Jessica");
		Console.WriteLine(phonebook.Count);
    }
}

Strings

Combining elements together into a string.

string fruit = "apple,orange,banana";
Console.WriteLine("Found orange in position: " + fruit.IndexOf("orange"));
Console.WriteLine("Found lemon in position: " + fruit.IndexOf("lemon"));
Posted In CategoriesC#| Tagged Tags