overview edit doc new doc remove

Jan 26, 2018

C sharp

Microsoft's capitalistc wannabe a good programming language.

Basics

Syntax

Comments

/* multiple line
comment*/

// one line comment

Datatypes

var can hold any datatype once.

bool hasWater = true;
char grade = 'A';
int maxInt = int.MaxValue;
string message = "message";
long maxLong = long.MaxValue;
decimal maxDec = decimal.MaxValue;
float maxFloat = float.maxValue;
double maxDouble = double.maxValue;
var anotherName = "Tom"; 

If else

if(num1 > num2) {

  Console.WriteLine("");  

} else if (...) {

  ...

}
Shorter
bool canDrive = age >= 16 ? true : false;

Loops

While
while(i < 10) { .. }
Do while
do { } while ( )
For
for (int i=1; i<10; i++ ) { .. }
Foreach
string randStr = "AbCdE";
foreach(char c in randStr) { .. }
Switch
switch (age) {case 0: Console.WriteLine("zero"); break; default: ...}

Printing and scanning

printf("\" \' \/ ");
Console.Write("What is your name? :");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name);
Console.WiteLine("Hello {0}", name);

Casting

double pi = 3.14;
int intPi = (int)pi;

String to int

A string isn't an int in terms of static analysis, so no cast is possible. So to convert string to int you should use parsing:

string stringA = "123";
int intA = int.Parse (stringA);

Random numbers

Random rand = new Random()
Console.WriteLine ("Random number betweel 1 and 10" + (rand.Next(1,11)));

Strings

A string is a bunch of individual characters.

string name = "Sebastiaan";

To print a string:

Console.WriteLine ("Hello " + name);

To concat strings use:

stringA ("Hello ");
stringA += ("Sebastiaan");
String.Concat (stringA, stringB);

To get the length of a string use:

stringA.Length;

To compare two strings use:

stringA.Equals ("15");

To check if a string is empty:

String.ISNullOrEmpty (stringA);

To get the index of a character use:

stringA.IndexOf ("gA");

To transform it to a substring:

stringA.Substring (2,4);

Using the StartsWith method. Returns True or False.

stringA.StartsWith ("str"); 

To trim a string:

stringA.Trim();

Replace and remove:

StringA.Replace (stringA, "test");
stringA.remove (0,2);

To format a string use:

decimal decimalA = 17.25;
String stringB = String.Format ("decimalA is equal to {0:C2}", decimalA);

StringBuilder

StringBuilder sb = new StringBuilder();

sb.Append ("Hello");
sb.Append ("Sebastiaan");

sb.Replace ("a","e");

Console.WriteLine (sb.ToString());

Arrays

string[] names = new String[3]
Console.WriteLine ("NameList" + String.Join (",",names));

int[] randNumbers;
int[] randArray = new int[6];
int[] randArray2 = {1, 2, 3, 4, 5};

Get the length of an array:

randNumbers.Lenght;

To print an item. For example print out the second item:

Console.WriteLine(randNumbers[1]);

To search for use:

Array.IndexOf(randArray2, 4);

String to array to string:

string[] names = {"Tom", "Mark" , "Jan"};
string namesStr = String.Join (",", names);
string[] namesStrArray = namesStr.Split (",");

Multidimensional array

int[,] multi = {{5,4},{9,8}};

Looping trough multidimensional array:

for (int x=0; x<multi.GetLenght(0);x++) {

  for (int y=0; y<multi.GetLenght(0);y++) {

    Console.WriteLine ("{0} | {1} : {2}", x, y, multi[x,y]);

  }

}

Lists

Lists is like an array but unlike an array it will automatically resize when adding or deleting items.

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

To add items to the list:

listA.Add(5);
int [] arrayA = {1,2,3};
listA.AddRange (arrayA);

Clearing the list:

listA.Clear;

Insert at specifc position:

listA.Insert (1, 10);

To sort list numerically or alphabetically:

listA.Sort();

Classes

class Animal {

  // variables, getters and setters

  // constructors

  // static fields

  // methods

}

// creating an object in main

Variables, setters and getters

To generate setters and getters automatically use:

public double height { get; set; } // generates setters and getters automatically
private double weight;
protected sound;

To set them manually use:

public string name;
public string Name {

  get { return name; }
  set { name = value; }

}

Constructors

The this keyword is a reference to the object that is being created.

public Animal () {

  this.height = 0;
  this.name = "No Name";
  ...

}

Using parameters

public Animal (double height, string name, ...) {

  this.height = height;
  this.name = name;
  ...
  numOfAnimals++

}

Static fields

A static field is used when it doens't make sense for the object to have, it is shared by any object created in the class.

static int numOfAnimals = 0;

Methods

public static int getNumOfAnimals () {

  return numOfAnimals;

}

public string toString () {

  return String.Format("{0} is {1} tall", name, height);

}

Overloading

It is possible to have the same methods with different datatypes.

public int getSum (int x, int y) {

  return x+y;

}
public double getSum (doulbe x, double y) {

  return x+y;

}

Creating objects

static void Main (string[] args) {

  Animal fluffy = new Animal (15, "Fluffy", ...);

  Animal goofy = new Animal {

    name = "Goofy";
    height = 8;
    ...

  };

  Console.WriteLine("Number of animals: " + Animal.getNumOfAnimals());

}

Inheritance

With Inheritance you can use poymorfism. For example you make an abstract class Shape, and 2 normal classes: Rectangle and Triangle and they inherit from Shape. Now you can make an object like: "Shape tri = new Triangle(..);".

Use inheritance by a : .

class Dog : Animal {

  ...

}

Abstract classes

Abstract classes are used to obtain a blueprint. The blueprint contains methods, you need to implement them when you inherit.

abstract class Shape {

  public abstract double area (); // abstract method

  public void sayHi () {

    Console.WriteLine ("Hello");

  }

}

NOTE: You can only inherit one abstract class.

Interfaces

Unlike abstract classes you are allowed to inherit multiple interfaces.

public interface ShapeItem {

  double area ();
}

Generics

With generics you don't have to specify the datatype of an element in a class or in a method.

class KeyValue<TKey, TValue> {

  public TKey key {get; set; }
  public TValue value {get; set; }

  public KeyValue(TKey k, TValue v) {

    key = k,
    value = v;

  }

  public void showData () {

    Console.WriteLine("{0} has value {1}",TKey,TValue);

  }

}

Create a generic object:

static void Main(string[] args) {

  KeyValue<int, string> key1 = new KeyValue<int, string>(0,"");
  key1.key = 78;
  key1.value = "54785";

}

Enumerated types

An enumerated type or enum is a unique type that will have a symbolic name and associated values. Enumeration contains its own values and cannot inherit or cannot pass inheritance.

public enum Season {

  Winter,
  Summer,
  Spring,
  Autumn

}

Set the enum in the main by calling:

Season seasonFirstYear = Season.Winter;

Structs

A struct is a custum type that will hold data for many different datatypes and it can also contain methods. The main difference between structs and classes is that structs are value types and classes are reference types.

A reference type lives on the heap which means a variable containing a reference type contains a pointer to the memory where the actual value resides.

On the other hand Value types lives inline, which means that a variable contains the entire struct, with all its fields.

In other words value types will always contain a value and reference types can contain a null-reference.

The greatest difference happens internally, in the memory. When copying the contents of a value type variable into another variable, it copies the entire contents into the new variable, making the two distinct. After the copy changing one will not affect the other. However when copying a reference type variable into another variable it actually copies the reference, which means you now have two references to the same memory location. After the copy changing the data in one reference will affect the other because you are actually just looking at the same data both places.

struct Customers {

  private string name;
  private int id;

  public void method () {
    ...

  }

}

Delegates

Delegates is used for passing methods as arguments to other methods. A delegate is a reference type variable that holds the reference to a method.

delegate double GetSuml (double num1, double num2);

namespace App {

  class Test {

    static void Main (string[] args) {

      GetSum sum = delegate (double num1, num2) {

        return num1+num2;

      };

      Console.WriteLine ("5+10= " + sum(5,10));

    }

  }

}

Lambda expressions

A lambda expression is an anonymous function or expression tree and it is mostly used to create delegates in LINQ. Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and name.

delegate double GetSum (double num1, double num2);

namespace App {

  class Test {

    static void Main (string[] args) {

      Func<int, int, int> GetSum = (x,y) => x + y;
      List<int> numList = new List<int> {5,4,9,5,7};

      //store odd numbers in a new list
      List<int> oddNums = numList.Where (n=> n% 2 == 1).ToList();

      foreach (int nr in oddNums) {

        Console.WriteLine(nr + ",");

      }

      Console.WriteLine ("5+10= " + sum (5,10));

    }

  }

}

Error handling

Divide by 0 error handling:

try {

  Console.Write ("Divide 10 by : ");
  int intA = int.Parse (Console.ReadLine());
  Console.WriteLine ("Solution: {0}",(10/intA);

} catch (DivideByZeroException ex) {

  Console.WriteLine ("Error!!");
  Console.WriteLine (ex.GetType().Name + ex.Message);
  throw new InvalidOperationException ("Failed", ex);

} catch(Exception ex) {

  Console.WriteLine ("Error!!");
  Console.WriteLine (ex.GetType().Name + ex.Message);
  throw new InvalidOperationException ("Failed", ex);

}

File I/O

To use file I/O you need to use a StreamWriter and a StreamReader.

string[] custs = new string[] {"Tom","Paul","Greg"};

using (StreamWriter sw = new StreamWriter ("custs.txt")) {

  foreach (string cust in custs) {

    sw.WriteLine (cust);

  }

}

string custName = "";

using (StreamReader sr = new StreamReader ("custs.txt")) {

  while ((custName = sr.ReadLine())!=null) {

    Console.WriteLine (custName);

  }

}
1