iankiku
8/12/2018 - 5:53 PM

C# csharpNippets

Useful csharp snippets

// ToString function
// To cast a non-string object into a string, use the built in 'object.ToString()' function. Casting with '(string)' will only work on objects that are already strings, so the ToString function is necessary when turning something like an int into a string.

int integer = 1;
string ourString = "Something to be replaced by an int";
ourString = integer.ToString();
System.Console.WriteLine(ourString);



// String formatting
// To format a string, use the String.Format function. Each additional argument to the function can be referred to in the string using the brackets operator with the index number. For example, {1} refers to the second argument provided for the format function.

int x = 1, y = 2;
int sum = x + y;
string sumCalculation = String.Format("{0} + {1} = {2}", x, y, sum);
Console.WriteLine(sumCalculation);




// Substring
// The Substring string method returns a part of the string, beginning from the index specified as the argument. Substring also accepts a maximum length for the substring.

string fullString = "full string";
string partOfString = fullString.Substring(5);
string shorterPart = fullString.Substring(5, 3);
Console.WriteLine(partOfString);
Console.WriteLine(shorterPart);



// Search and replace
// The Replace string method replaces an occurrence of a string with another string.

string name = "John Doe";
string newName = name.Replace("John", "Eric");
Console.WriteLine(newName);


// Index of
// The IndexOf string method finds the first occurrence of a string in a larger string. If the string is not found, -1 is returned.

string fruit = "apple,orange,banana";
Console.WriteLine("Found orange in position: " + fruit.IndexOf("orange"));
Console.WriteLine("Found lemon in position: " + fruit.IndexOf("lemon"));



// Use string formatting to format the variables firstName, lastName and age to form the following sentence into the string sentence:

// John Doe is 27 years old.
// Dictionaries
// Dictionaries are special lists, whereas every value in the list has a key which is also a variable. A good example for a dictionary is a phone book.

Dictionary<string, long> phonebook = new Dictionary<string, long>();
phonebook.Add("Alex", 4154346543);
phonebook["Jessica"] = 4159484588;


// Execute Code
// Notice that when defining a dictionary, we need to provide a generic definition with two types - the type of the key and the type of the value. In this case, the key is a string whereas the value is an integer.

// There are also two ways of adding a single value to the dictionary, either using the brackets operator or using the Add method.

// To check whether a dictionary has a certain key in it, we can use the ContainsKey method:

Dictionary<string, long> phonebook = new Dictionary<string, long>();
phonebook.Add("Alex", 415434543);
phonebook["Jessica"] = 415984588;

if (phonebook.ContainsKey("Alex"))
{
    Console.WriteLine("Alex's number is " + phonebook["Alex"]);
}



// Execute Code
// To remove an item from a dictionary, we can use the Remove method. Removing an item from a dictionary by its key is fast and very efficient. When removing an item from a List using its value, the process is slow and inefficient, unlike the dictionary Remove function.

Dictionary<string, long> phonebook = new Dictionary<string, long>();
phonebook.Add("Alex", 415434543);
phonebook["Jessica"] = 415984588;

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


// Execute Code
// Exercise
// Create a new dictionary called inventory that holds 3 names of fruits, and the amount they are in stock.
// Lists in C# are very similar to lists in Java. A list is an object which holds variables in a specific order. The type of variable that the list can store is defined using the generic syntax. Here is an example of defining a list called numbers which holds integers.

List<int> numbers = new List<int>();

/*The difference between a list and an array is that lists are dynamic sized, while arrays have a fixed size. When you do not know the amount of variables your array should hold, use a list instead.
 Once the list is initialized, we can begin inserting numbers into the list.*/
 
List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

// We can also add a whole array to a list using the AddRange function:

List<int> numbers = new List<int>();
int[] array = new int[] { 1, 2, 3 };
numbers.AddRange(array);


// We can use Remove to remove an item from a list by specifying the item we want to remove.

List<string> fruits = new List<string>();
// add fruits
fruits.Add("apple");
fruits.Add("banana");
fruits.Add("orange");

// now remove the banana
fruits.Remove("banana");
Console.WriteLine(fruits.Count);

// We can also use RemoveAt to specify an index of an item to remove. In our case, to remove the banana, we will use the index 1.

List<string> fruits = new List<string>();
// add fruits
fruits.Add("apple");
fruits.Add("banana");
fruits.Add("orange");

// now remove the banana
fruits.RemoveAt(1);
Console.WriteLine(fruits.Count);



// Concatenating lists
// We can use AddRange to join between lists.

List<string> food = new List<string>();
food.Add("apple");
food.Add("banana");

List<string> vegetables = new List<string>();
vegetables.Add("tomato");
vegetables.Add("carrot");

food.AddRange(vegetables);
Console.WriteLine(food.Count);


A Class with a generice list type
has getters and setters method
with two methods to add items to list and display all items from list

    public class Employee
    {
    
        public int EID { get; set; }
        public string EName { get; set; }
        IList<Employee> EmployeeList = new List<Employee>();

        public void CreateEmployee()
        {
           new Employee() { EID = 1, EName = "John Doe" };
        }

        public void DisplayEmployeeList()
        {
            foreach(var e in EmployeeList)
            {
                Console.WriteLine("Employee List : {0}", e.EName);
            }
        }

    }
// innitialised array
int[] nums = { 1, 2, 3, 4, 5 };

// empty array
int[] nums = new int[10];
int[] nums = new int[10];
Console.WriteLine(nums.Length);


// To access a specific item in the array, we use the brackets operator:

int[] nums = new int[10];
int firstNumber = nums[0];
int secondNumber = nums[1];
nums[2] = 10;




// multi-dimentional array

int[,] matrix = new int[2,2];

matrix[0,0] = 1;
matrix[0,1] = 2;
matrix[1,0] = 3;
matrix[1,1] = 4;

int[,] predefinedMatrix = new int[2,2] { { 1, 2 }, { 3, 4 } };  
// To define a variable in C#, we use the following syntax, 

int myInt = 1;
float myFloat = 1f;
bool myBoolean = true;
string myName = "John";
char myChar = 'a';
double myDouble = 1.75;



// Enums are integers that should be used when an integer is used to specify an option from a fixed amount of options.
public enum CarType
{
    Toyota = 1,
    Honda = 2,
    Ford = 3,
}

public class Tutorial
{
    public static void Main()
    {
        CarType myCarType = CarType.Toyota;
    }
}
  // Array sort
  // bubble sort
  
  
  // linear sort
  
  
  
  
  
// basic int[] adult_ages = { 21, 23, 24, 28, 30, 31};
            int[] kids_ages = { 1, 9, 7, 4, 3, 5, 13 };
       
           


            //char[] names = { 'ian', 'asong' };

            Console.WriteLine("Hello World!");
            // Console.WriteLine(ageArray[3]);
            // Console.WriteLine(names);
            // Array.Copy(sourceArray, destArray, 2);
            int[] copy = new ;
            Array.Copy(adult_ages, copy, copy.Length);

            // Array.Sort(Array);
            // Array.IndexOf(Array, value)

           
           foreach (var items in copy)
            {
                Console.WriteLine(items);
                Console.ReadLine();
            }
// C# method characteristics
// Basic characteristics of methods are:

// Access level
// Return value type
// Method name
// Method parameters
// Parentheses
// Block of statements
<Access Specifier> <Return Type> <Method Name>(Parameter List) {
   Method Body
}

public 
// How Constructors are defined in C#

int a = 10;
int b = 20;
int c = 5;

var result = a > b ? " false" : 
             b > c && b > a ?   " true b is greater c and a" : " b is greater and c is less";

Console.WriteLine(result);
//

int a = 10;
int b = 20;
int c = 15;
int d = 3;

switch(d){
    case 0:
    Console.Write("...Complete");
    break;
  case 10:
  Console.WriteLine(10);
  break;
  
  case 15:
  Console.WriteLine(15);
//   nested switch block
    switch(c - 10){
            case 5:
            Console.WriteLine( "c is > 3");
            
            break;
    }
goto case 0;
  
  case 20:
  Console.WriteLine(20);
  break;
  
  default:
  Console.WriteLine("None Matched");
  break;
}


struct Employee{
    public int EmpID;
    public string fname;
    public string lname;
    public string fullname;
// without constructor
}

// Employee emp;
// Console.WriteLine(emp.EmpID);
// emp.EmpID = 123;
// Console.WriteLine(emp.EmpID);

// with constructor
struct EmployeeCorp{
    public int EmpID;
    public string FirstName;
    public string LastName;
    public string Email;

    public EmployeeCorp(int empid, string fname, string lname){
        EmpID = empid;
        FirstName = fname;
        LastName = lname;
        Email = $"{fname}.{lname}{empid}@email.com";
    }
}


EmployeeCorp prime = new EmployeeCorp(123, "ian", "kiku");

// convert int to string 
string id = prime.EmpID.ToString();

Console.WriteLine(id.ToUpper());
Console.WriteLine($"Full Names : {prime.FirstName.ToUpper()},  {prime.LastName.ToUpper()}");
Console.WriteLine($"Employee Email: {prime.Email}");