C# Overview

This is an overview of many fundamental programming concepts common to most programming languages.

Visit dotnetfiddle.net to write and execute any of the code snippets in this lesson. Add the code you want to run in the Main method as follows:

Test the code by pressing the Run button at the top of the page.

What is C#?

A program is just a list of instructions that tells the computer what to do. What happens when the user presses a certain button? What happens when two objects collide? The code within a program written in some programming language determines this.

C# (i.e. "C sharp") is one of the programming languages you can use when creating programs in the Unity engine. The engine itself already has a great deal of code written for us, such as the code to display 3D objects and to apply physics to those objects.

You will not have to write code to make an object fall or to make a ball roll as Unity has already provided this for us. However, you will need to write code, or use code others have written, for other behaviors you want to implement.

Basic Concepts of Computer Programming

1. Syntax
The syntax of a computer language is equivalent to the spelling and grammar of natural languages. When syntax rules of a language are not followed exactly, the computer will not understand the instructions you are providing and a "syntax error" will result when the code is compiled. C# has a similar syntax to all C type languages. That is, programming languages such as Java, C++, JavaScript, and C# all use similar syntax to the original C programming language. All of these languages are case-sensitive, so even a mistake in capitalization within the code is a syntax error. Also, in all C type languages each instruction, or command, ends with a semi-colon.

2. Variables
Variables are used to store information. In C#, the proper syntax for declaring (i.e. creating) a variable with a name of score and an initial value of 0 is:

int score = 0;

C# is a "typed" language, meaning the type of value that is to be stored must be specified when any variable is declared. A variable that will store integers (e.g. -10, -3, 0, 1, 25, etc.) should be of type int; a variable that will store characters (e.g. "Bob", "Star Wars", etc.) should be of type string; a variable that will store decimal values (e.g. -12.5, -3.0, 0.001, 1.9, etc.) should be of type float or of type double; a variable that will store the value of true of false should be of type bool; and so forth.

Always use meaningful variable names to improve code readability. The name score would be more appropriate than the name a for a variable being used to store the score of a game.

3. Operators
Operators (such as +, +=, =, ==, !, !=, <, >, etc.) are symbols that have specific functionality within a programming language. For instance, the = operator is the assignment operator used to assign values to variables; and common mathematical operators include + for addition, - for substraction, * for multipication, and / for division.

Conditional operators include < to compare if one value is less than another, > to compare if one value is greater than another, and == to check if two values are equal.

The ! operator is the negation operator and can be read as "not". So, the != operator can be read as "not equal" and is used to check if two values are not equal. Other conditional operators include <=, read as "less than or equal to"; and >=, read as "greater than or equal to".

In C#, the + operator is used for addition when used with numeric values, but is also used for concatination when used with strings (e.g. combining two strings, or sets of characters, together into one string). For instance, the following code will use the + for addition and print (using the Console.WriteLine function) the sum of the two variables (i.e. 12) to the Console Window within Unity.

int a = 5;
int b = 7;
Console.WriteLine(a + b);

However, the code below will use the + for concatination and print racecar to the Console.

string a = "race";
string b = "car";
Console.WriteLine(a + b);

Other mathematical operators that are useful include += to increase by, -= to decrease by, *= to multiply by, and /= to divide by. For instance, if you want to increase the value of a variable named score that was previously declared by 5, you could write:

score = score + 5;

In this case, score is being assigned the value of the current value of score plus 5 more.

or you could simply write:

score += 5;

which has the same effect of increasing the current value of score by 5.

Increasing or decreasing by one is so common that an additional shortcuts were created. The ++ operator may be used to increase by 1 and the -- operator may be used to decrease by 1. In the following code, score is declared and given an intial value of 7, then the value is increased by 1 to be 8, then the value is multipled by 2 to be 16, then the value is decreased by 1 to be 15, then the final value of the variable (15) is printed to the Console.

int score = 7;
score++;
score *= 2;
score--;
Console.WriteLine(score);

Interestingly, the programming language "C" was renamed to "C++" when many new features were added to the language, including the ++ operator.

4. Conditional Statements
Conditional statements are used in programming language to execute code (run the program) only if a condition is true. For instance, the following code will print You Win to the Console only if the value of score is 5.

if(score == 5) Console.WriteLine("You Win");

Curly braces (i.e. { and }) are used in C# to group together a code snippet into a block. This is useful with conditional statements when more than one command should be executed. For instance, in the following code, if the value of score is less than 5, the value of score will be increased by one and print the new value to the Console.

if(score<5){
   score++;
   Console.WriteLine(score);
}

if statements (the most commonly used conditional statements) may include an else to execute code when the condition in the parenthesis fails. For example:

if(firstName=="Jake"){
   Console.WriteLine("What a great guy!");
}
else{
   Console.WriteLine("I do not know you " + firstName);
}

In this case, if the value of firstName is "Jake", What a great guy! is printed to the Console. Otherwise, if the condition fails, code inside the else block exectures instead. Notice that the plus sign is being used to concatinate the two strings together.

The condition in the parenthesis can have multiple parts, using the && operator for "and" and the || operator for "or". For example, the programming is fun message in the below code is only printed to the Console if excitementLevel is greater than 3 AND timeDevoted is greater than or equal to 30.

if(excitementLevel > 3 && timeDevoted >= 30) Console.WriteLine("programming is fun");

Each condition within an if statement evaluates down to either true or false. In the above example, both conditions would need to evaluate to true for the entire expression to be true. If the || operator was used between the conditions instead of the && operator, only one of the conditions would need to evaluate to true for the entire expression to evaluate to true.

Boolean variables (i.e. variables of type bool that have a value of true of false) can be used inside of conditional statements without conditional operators. For instance, if a boolean variable named isPaused has a value of true, the two equivalent lines below would each print sweet to the Console.

if(isPaused == true) Console.WriteLine("sweet");
if(isPaused) Console.WriteLine("sweet");

The latter is recommended.

The ! operator may be used with a boolean variable to negate its value. For instance, if a boolean variable named isPaused has a value of false, the three equivalent lines below would each print sweet to the Console.

if(isPaused != true) Console.WriteLine("sweet");
if(isPaused == false) Console.WriteLine("sweet");
if( ! isPaused) Console.WriteLine("sweet");

The latter is reccommended.

5. Debugging
A program that has errors (or bugs) will result in unintended behavior or will not run at all. All programmers make errors. Good programmers learn effective "debugging" strategies to identify the errors. Below are just a couple of commonly used strategies to debug broken code.

First, outputting messages or values of variables to the Console using the Console.WriteLine() function is often helpful. This method can be used to determine if a section of code is or is not being executed, and to determine if variables have the values that are expected or not.

Another method for debugging code is to "comment out" code to see how the program runs without the code. Two forward slashes can be used to comment out one line of code. In the code below, the commented out line would be ignored when the program runs, and the value printed to the Console would be 7.

int score = 7;
score++;
// score *= 2;
score--;
Console.WriteLine(score);

Sometimes it is helpful to comment out larger blocks of code. In such a case, /* and */ may be used before and after any number of lines to comment out an entire block of code. In the code below, the commented out lines would be ignored when the program runs, and the value printed to the Console would be 8.

int score = 7;
score++;
/*
   score *= 2;
   score--;
*/

Console.WriteLine(score);

Comments, as the name suggests, are also useful for programmers to add notes into the program for themselves and other programmers.

6. Loops
Loop structures are used to repeat a block of code. A while loop will repeat a block of code until a condition is true. For instance, in the following code DO SOMETHING will be printed to the Console five times.

int x = 0;
while(x<5){
   Console.WriteLine("DO SOMETHING");
   x++;
}

When using a loop structure, be careful not to create an infinite loop that will crash the program because it never stops executing.

int x = 0;
while(x<5){
   Console.WriteLine("DO SOMETHING");
}

Another common loop structure is the for loop. An example of a for loop is as follows:

for(int i=0; i<3; i++){
   Console.WriteLine("DO SOMETHING");
}

Notice there are three parts of a for statement, separated by semicolons, within the parenthesis. The first part defines a variable with an initial value. The second part is the condition that determines if the code should be executed again, and the third part is used to change the value of the variable after each time the code in the block is executed. In the above example, the message is printed to the Console three times; once when the value of i is 0, once when the value of i is 1, and once when the value of i is 2.

Consider another example:

for(int j=4; j>=0; j-=2){
   Console.WriteLine(j);
}

In this example, the variable being used is j and is initialized with the value of 4. The code in the block exectues repeatedly while j is greater than or equal to 0, and every time the code executes the value of j is decrease by 2. So, 4 is printed to the Console the first time the code executes, 2 is printed to the Console the second time the code executes, and 0 is printed to the Console the third and last time the code executes.

7. Functions
Explain and give examples of functions.

8. Event Listeners
One of the challenges to new programmers is figuring out where to put code. Sometimes you want a code snippet to run right when the program begins. Other times you want code to run when a a key on the keyboard is pressed, or the user clicks on or hovers over something with the mouse. Still, other times you want code to run when the loading of a sound finishes, or when a collision between two elements occurs. The list goes on and on. In all of these cases, event listerners will help. The basic idea is that you can "turn on" an event listener to detect when a particular event occours and write a block of code (an event handler) that will execute at that precise moment.

9. Data Structures
While a variable is useful for storing one value, data structures (Arrays, Hash Tables, Trees, Binary Trees, etc.) are used to store sets of data (i.e. multiple values). Every data structure has different strengths and weaknesses in regard to how data is stored and retrieved.

An array is one of the most common data structures that you will expect to see in almost every programming language, including C#. An array is like a variable, except that it can hold many values instead of just one. Consider a visual representation of a variable:

age
22

Here, age has the value of 22 and is of type int signifying that the values stored in the variable will be integers. It can have any integer value, but only one. You declare a variable using:

int age;

You assign a value to a variable using:

age = 22;

You can also assign a value at the same time you declare the variable:

int age = 22;

You may use variables to store numbers (integers and decimals), strings (comprised of numbers, letters, and other characters), Boolean values (true and false), and even Objects (such as an array).

An array named ages could be visualized like this:

ages
22
18
31
25
22

0
1
2
3
4

Here, ages has multiple values of 22, 18, 31, 25, and 22. It can have any number of values. The index (shown here in red) is used to specify an element of the array. The first element of an array always has an index of 0. The array above has a length of 5, with index values from 0 to 4.

You declare an array of type int using:

int[] ages = new int[2];

The above code creates an array that can hold two elements. In C#, the size of an array is fixed so cannot change in size as the program runs.

You assign a value to an array using:

ages[0] = 22;
ages[1] = 18;

You can also assign a value at the same time you declare the variable:

int[] age = new Array(22, 18, 31, 25, 22);

In some programming languages, arrays are not fixed in size. If you are used to using dynamic arrays (those that are able to change in size as the program runs), you may find arrays in C# limiting. If you need to store data in a structure that changes in size, a good option is the list object.

List list = new List<Student>();
list.Add(new Student("bob"));
list.Add(new Student("joe"));

Basic Concepts of Object Oriented Programming

1. Encapsulation (objects and classes)
brief simple description

2. Abstraction (instances)
brief simple description

3. Inheritance (parents, children, and siblings)
brief simple description