Basic C# Cheat Sheet

Basic Variables

2

Operators in C#

3

Type Conversion in C#

5

Comparing Stuff in C#

6

Loops in C#

7

Arrays in C#

8

Methods in C#

9

Classes in C#

10

Inheritance in C#

12

Exceptions in C#

13

1

Basic Variables Variables are the smallest practical working blocks of any application. They are essentially small pieces of data stored in special purpose containers.

Storing a number: int myNum = 9;

(‘int’ stores a whole number)

double myNum = 9.879;

(‘double’ stores a decimal number)

float myNum = 10.876587f;

(‘float’ stores a decimal number - note the ‘f’ ending)

Storing words or letters string myText = “I like this sheet”;

(‘string’ stores characters or sequences of them)

Variables are the basic building blocks of all software. They cannot be mixed so you cannot store an int inside of a string or vice versa.

2

Operators in C# Operators allow sums between numbers to take place. They also allow concatenation of strings (adding words onto other words).

Adding a number: int myNum = 9; int otherNum = 10; int result = myNum + otherNum; (The result would be equal to 10) Subtracting a number: int myNum = 9; int otherNum = 10; int result = myNum - otherNum; (The result would be equal to -1) Multiplying a number: int myNum = 9; int otherNum = 10; int result = myNum * otherNum; (The result would be equal to 90) Dividing a number: int myNum = 9; int otherNum = 10; int result = myNum / otherNum; (The result would be equal to 0). Wait what? Well, ‘int’ can only hold a whole number and 9 / 10 = 0.9. Therefore ‘int result’ simply drops the ‘.9’ part! Be careful when performing arithmetic!

3

Adding strings string myText = “I like this sheet”; string myOtherText = “Oh I really do!”; string fullSentence = myText + “. “ + myOtherText; (Result = “I like this sheet. Oh I really do!”;

4

Type Conversion in C# You can’t mix types in C# but you can convert between them (with some limitations);

Convert from most types to string: int myNum = 90; string result = myNum.ToString(); (The result would be the word “90”)

Convert from string to number: string myText = “98”; int myNum = Convert.ToInt16 (myText); (Result is number 98); WATCH OUT! Following throws an app crashing error: string myText = “Grant”; int myNum = Convert.ToInt16 (myText);

BIG ERROR HERE!

Why an error? You cant convert a word to a number so your app will kick and scream, bringing the whole thing down. Avoid type conversion where possible.

5

Comparing Stuff in C# What if my numbers are equal and I want to know?

if else statements: int myNum = 9; if (myNum == 9) { (this code executes if myNum is 9) } else if (myNum == 10) { (this code executes if myNum is 10) } else { (this code executes if none of the above is true) }

switch case statements: int myNum = 10; switch (myNum) { case 10: (this code executes if myNum is 10) break; case 12” (this code executes if myNum is 12) break; default: (this code executes if myNum is none of above cases) break; }

6

Loops in C# Round and round until we meet some condition

while loops: int i = 0; while (i < 100) { (run code in here each time we go around and i is less than 100) i++; (adds one to i each time we go around) } (while loop ends when i is 100 or more)

for loops: These are kind of like while loops but with a little more control for (int i = 0; i < 100; i++) { (run code in here each time we go around and i is less than 100) } (for loop ends when i is 100 or more)

7

Arrays in C# What if you’d like to hold a list of items, all of the same type?

Create a string array: string [ ] myArray = new string [ ] { “Grant”, “Learn”, “App”, “Development” };

Create an integer array: int [ ] myArray = new int [ ] { 3, 98, 9874, 236763276327 };

Get elements out of array: var secondItem = myArray [1]; (Why do you write ‘1’ and not ‘2’ to get second element? Because all indexing in C# is based on numbers starting at ‘0’ so our program counts - 0, 1, 2, 3 etc. )

How long is your array or how many elements does it have? int arrayLength = myArray.Length;

8

Methods in C# What if you want to do stuff to your variables? It would be horrible to write ‘myNum + otherNum’ EVERY time you needed it. Methods allow you to store that code in one place that can be accessed multiple times and from multiple places.

A method to add stuff: public void AddNumbers (int myNum, int otherNum) { int result = myNum + otherNum; } public - means the method is accessible by other parts of your program. void - means the method doesn't return anything. (int myNum, int otherNum) - these are arguments. Arguments are values handed over to the method, necessary for it to do what it does. A method can have no arguments if none are needed.

Calling a method: AddNumbers (9, 10); Can you see how this cuts down on repetitive code?

9

Classes in C# You have variables and methods now. Where should you put them? In classes! Classes have 2 objectives - the first of which is to organise your code. C# also generally expects variables and methods to be enclosed in classes - it’s kind of obsessive like that!

Define a class: public class MyCar { int topSpeed; string color; public MyCar (int _topSpeed, string _color) { topSpeed = _topSpeed; color = _color; } public int GetTopSpeed ( ) { return topSpeed; } public void PaintCar (string newColor) { color = newColor; } }

The second thing classes do is become blueprints for types of objects. In this case the class holds a blueprint for a car.

Make some cars: MyCar toyota = new MyCar (100, “Red”); MyCar ferrari = new MyCar (200, “Blue”);

Change their colors: toyota.PaintCar(“Green”); ferrari.PaintCar(“Red”);

10

Get their top speeds: int toyotaTopSpeed = toyota.GetTopSpeed ( ); int ferrariTopSpeed = ferrari.GetTopSpeed ( );

Classes are mighty useful for defining new kinds of objects and VASTLY reducing code reuse. Making objects from classes is one of the core principles of ‘Object Oriented Programming’. You may see this abbreviated to OOP in some places.

11

Inheritance in C# Classes don’t have to be redefined every time you make them. They can ‘inherit’ other class properties and methods.

Define a Vehicle class: class Vehicle { int topSpeed; string color; }

Make a Truck class: class Truck: Vehicle { (truck inherits from vehicle so truck also has a topSpeed and color) }

Make a Car class: class Car: Vehicle { (car inherits from vehicle so car also has a topSpeed and color) }

12

Exceptions in C# Not what you might think! An exception in C# means something happened that wasn't expected or allowed. The result? CRASH! Your whole program gives up.

Something that causes an exception: string myName = “Grant”; int myNum = Convert.ToInt16 (myName); CRASH HAPPENS HERE BECAUSE ‘GRANT’ is not a number so can’t be changed to an int

How do we solve this? 1. DON’T DO IT IN THE FIRST PLACE! Think before you type. 2. Sometimes you can’t avoid these things (eg, if calling out to a web service) If you expect something to fail you can use a ‘try’ ‘catch’ statement.

Try catch statement: string myName = “Grant”; try { int myNum = Convert.ToInt16 (myName); } catch (Exception e) { (code to execute when error is thrown) (the Exception ‘e’ contains all the details in ‘e.Message’) } If try fails then catch is run, giving you a chance to inform the user something is wrong - all without an horrendous app crash!

13