Category Archives: C# Basics

Lesson 8: Error and Exception Handling

An exception is an unforeseen problem that arises when you execute a program. Most of the time, your program should check for these problems, and handle them transparently and in a user friendly way. Infact, you should always build in ways to check for problems in your code, by verifying input, validating data, checking for nulls, etc. However, there are times where there are stuff that you can’t predict, like out of memory errors, file errors, or database errors. This is where exception handling comes into place.

When an exception happens, it is called ‘thrown’. So when and exception happens, and exception is thrown.
Here are some common exceptions:

Exception Class Description
System.IO.IOException Handles I/O errors.
System.IndexOutOfRangeException Handles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchException Handles errors generated when type is mismatched with the array type.
System.NullReferenceException Handles errors generated from deferencing a null object.
System.DivideByZeroException Handles errors generated from dividing a dividend with zero.
System.InvalidCastException Handles errors generated during typecasting.
System.OutOfMemoryException Handles errors generated from insufficient free memory.
System.StackOverflowException Handles errors generated from stack overflow.

 

Most exceptions are thrown automatically by the program, however, you can throw you own exceptions.

To deal with exceptions, you use a Try – Catch statement. The try catch statement looks like this:

try
{
   // statements causing exception
}
catch( ExceptionName e1 )
{
   // error handling code
}
finally
{
   // statements to be executed
}

Here is an explanation of the Try-Catch statement:

  • try: A try block identifies a block of code for which particular exceptions will be activated. It’s followed by one or more catch blocks.
  • catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
  • finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown.

Here is an example, where we divide by zero.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lesson8_Errors
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
            division(65, 0);
            }
            catch( System.DivideByZeroException e)
            {
                Console.WriteLine(e);
                Console.WriteLine();
                Console.WriteLine("You tried to divide by 0! SKRUB!");
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
                Environment.Exit(0);

            }
            finally
            {
                Console.WriteLine("you finished you pleb");
            }
            Console.ReadKey();
        }
        public static void division(int yolo, int swag)
        {

            int division = yolo / swag;
            Console.WriteLine(division);
            Console.ReadKey();
        }
    }
}

Lesson 7: Classes

We have moved onto classes. Classes is one of the final major concepts in basic C# before we are finished. So what is classes? Classes are blueprints of code, that groups together variables, methods, and events. The classes themselves do not hold any data, however, they consists of what variables and methods that defines what the object will do. Instead, classes are like custom types. In OOP, a object is an instance or a copy of a class.

For example, you might have multiple instances of a car class, and each instance is called an object. You might have a mustang object, and a civic object. While the two might have different attributes, in a class they might have a few things declared that can be used for both.

To declare a class, it is very simple. Just use the word ‘class’ followed by a name. You will need a access modifier in front of it. For example:

public class Customer
{
//Fields, properties, methods and events go here...
}

Thats is it!
A class is often used for grouping code that has a similar purpose, with the ability to be different from eachother.
A quick note is that to access something inside the class you will need to use a dot. Confused? Take the Console class for example.
The console class is a class that has the purpose of grouping code that deals with the console. Inside there are methods and variables.
To print to the console, you use the WriteLine method. To do that, we use a dot, like so:

Console.WriteLine("WORDS");

To make new objects we use the work new, like how we made new Lists. As you can see, the class name is a custom type, and the object name can be whatever. We do it in this fashion:

//if you have a class called rito
rito myObjectName = new rito();

In C# you can also inherit classes. This mean you can make a class that haves everything that another class has, but you can extend it, by added variables and methods only necessary to the extension. For example you have a employee class that has stuff for general employee info. You now need a manager class. Instead of remaking everything, just to put some manager specific variables, you can inherit classes.

public class Manager : Employee
{
    // Employee fields, properties, methods and events are inherited 
    // New Manager fields, properties, methods and events go here...
}

Finally in an class, there is a special method called the constructor. This method is automatically ran when you make a new object from a class. This is useful because you can also pass information through the parameters of a class, or preparing the object by filling it in with information and data. Here is an example:

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Length of a line
      public Line()
      {
         Console.WriteLine("Object is being created");
      }

      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line();    
         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());
         Console.ReadKey();
      }
   }
}

Here is a full example of a class and object:

public class Person
{
    // Field 
    public string name;

    // Constructor that takes no arguments. 
    public Person()
    {
        name = "unknown";
    }
yolo (deny said this) teehee
    // Constructor that takes one argument. 
    public Person(string nm)
    {
        name = nm;
    }

    // Method 
    public void SetName(string newName)
    {
        name = newName;
    }
}
class TestPerson
{
    static void Main()
    {
        // Call the constructor that has no parameters.
        Person person1 = new Person();
        Console.WriteLine(person1.name);

        person1.SetName("John Smith");
        Console.WriteLine(person1.name);

        // Call the constructor that has one parameter.
        Person person2 = new Person("Sarah Jones");
        Console.WriteLine(person2.name);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
// Output: 
// unknown 
// John Smith 
// Sarah Jones

In Visual Studio, when you are creating a new class, it is recommended you create a new file, to keep organized, and to speed up the workflow. To do that, in your solution explorer, right click your solution, press ADD and press class.

Please visit this link when you are done to review:
http://www.tutorialspoint.com/csharp/csharp_classes.htm

Lesson 6: Functions/Methods

In the previous lessons, you have been putting your code in the “Main”. The main is a function (AKA methods). Methods is a group of statements and code that perform a given task. This is useful because you can use a method multiple times without rewriting the code. To use a method you have to define a method, and you have to call (run) the method latter on.

In C# the method structure is similar to Java.

<Access Modifier> <Return Type> <Method Name>(Parameter List)
{
   Method Body
}

An access modifier determines the visibility and accessibility of a method, class, variable, etc. in other classes and methods. This is like setting permissions of the method, and whether other classes can use this method. This is useful for separating classes and methods from interfering with each other, and is a key component of encapsulation and object-oriented programming in general. Here is a chart explaining the different access modifiers, in C#, C++ and Java.

Keyword C# C++ Java
private class class class
protected internal same assembly and
derived classes
protected derived classes derived classes derived classes
and/or
within same package
package within its package
public internal same assembly
public everybody everybody everybody

The return type specifies the type of the information returned, if there is information to be returned to where the function is called. The return types are usually the the type of the information return (eg. int if ints are returned). Void is used if no information is returned.

The method name is the name of the method. Pretty straight forward. (Warwick is OP btw)

Lastly there is the parameter list. The parameter list is used to pass information to the method. When an method is called, and parameters are passed, the method can use these parameters and process them accordingly. Parameters are what is given to the method, and the when the parameters are used in a method they are called arguments.

Sometimes the keyword static is used. This just means that there is only 1 instance of the code, and can be run as is, instead of being created in a new object first.
Here is a simple method, where it is called latter on in the code. :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace methods
{
    class Program
    {
        public static void myMethod(string stuff)
        {
            Console.WriteLine("myMethod prints the parameter stuff. Here it is: {0}", stuff);
        }
        static void Main(string[] args)
        {
            //We will now run myMethod with the argument Draven
            myMethod("Draven");
            Console.ReadKey();
            //the output:
            //myMethod prints the parameter stuff. Here it is: Draven
        }

    }
}

A neat thing that you should know that is awesome is that you can pass references in a method in C#. This means that you can pass a reference to an object, and the method will execute command as if it is on the other object accordingly. So it will pass what is directly in the memory at that time, instead of a copy of the variable passed through.

If you need more help, take a look at one of these pages:
http://www.csharp-station.com/Tutorial/CSharp/Lesson05
http://www.tutorialspoint.com/csharp/csharp_methods.htm
http://msdn.microsoft.com/en-us/library/ms173114.aspx

Lesson 5: Arrays and collections

Woot! We are almost half way there! Anyways, we have come to one of the more difficult sections of programming. Arrays requires you to use everything you have learned so far. If you need to, take some time to review the last few lessons.

Here is a vocab refresher:

  1. Declare means to name and make a variable, object, etc. This usually reserves a space in the memory, so don’t pull a ubisoft and waste all the space!
  2. Initialization means to fill the variable or object that you have declared with data.

Arrays

What is an Array? An array is a series of objects or variables that are the same type.
Arrays in C# work similarly to how arrays work in everything else, including Java. However, there are some minor differences. First thing you should know is that arrays in C# are written differently.

When declaring an array, the square brackets ([]) must come after the type, not the identifier(name). Placing the brackets after the identifier is not legal syntax in C#.

int[] table; // not int table[];

Secondly, the size of the array is not part of its type as it is in other C like languages. This allows you to declare an array and assign any array of int objects to it, regardless of the array’s length. If you don’t get this, it doesn’t really matter, as it just means that arrays are slightly more flexible.

Now that we got the differences over with for all those keeners out there, we move on to a refresher on what arrays look like. Arrays are declared in the following format:

datatype[] identifier;

Here is what it means:

  • datatype states the type of data being stored, like an int or a string
  • [ ] specifies the rank of the array. The rank specifies the size of the array.
  • identifier is the name of the array

Things in an array are called elements, and each element has a number, similar to an address. These are called indexes. Indexes always start with 0, because in programming, numbers start counting from 0. For example if you have the following code, Yasuo will be index 0 and Katarina will be index 1.

string[] rito = {"Yasuo","Katarina"};
//and therefore
//rito[0] == "Yasuo"
//rito[1] == "Katarina"

But before we dive into the different parts of arrays, and how to use them, lets look at types of arrays.

As with Java, there are 3 types of arrays.

  1. Single-Dimension Array
  2. Multidimensional Array
  3. Jagged Array

Single-Dimension Array are your normal arrays. Since arrays are series of things, and single-dimension array is just 1 series of things in a single line. EZ.

Multidimensional array are arrays arrays the are not just in a straight line, but in multiple dimensions. The most common is the rectangular or the 2D array. The first index is the one dimension, while the next one is the second. Think of them as a table, where the first index is the row number and the second index is the column. Take a look at this table:

Column 0 Column 1 Column 2
Row 0 a[0,0] a[0,1] a[0,2]
Row 1 a[1,0] a[1,1] a[1, 2]
Row 2 a[2,0] a[2,1] a[2,2]

 

Finally, Jagged arrays are arrays of arrays. Yes, they are just arrays in one of the indexes of an array. Arrayception!

So how do we declare arrays? Here is the format:

datatype[] identifier;

And here is an example:

//normal arrays
string[] listOfNames;

//multidimensional arrays
string[,] names;

//jagged arrays
string[][] names;

Thats is it! Declaring arrays in C# does not assign it in the memory. That mean declaring arrays does not mean you actually made an array! They must be initialized. When you have finished declaring an array, you can initialize it with stuff.
To initialize arrays you do the following:

//normal 1D arrays
int[] numbers = new int[5]; /* or */
int[] numbers = new int[];

//multidimensional arrays
string[,] names = new string[5,4];

//jagged arrays
byte[][] scores = new byte[5][];
for (int x = 0; x < scores.Length; x++) 
{
   scores[x] = new byte[4];
}

There are multiple ways of putting or retrieving information in an array. Here is the few ways you can do this:

//You can do it by index number
int[] sample = new int[];
sample[0] = 9;
sample[1] = 45;

//at the time of declaration like this
int[] sample = {9, 45};

//or like this
int[] sample = new int[]  {9, 45};

//or from another array
int[] temp = {9, 45}
int[] sample = temp;

//You can also specify the size of your array when creating an array
int[] sample = new int[2]  {9, 45};

and it is very similar for the different types of array:

//multidimensional
int [,] a = int [3,4] = {  
 {0, 1, 2, 3} ,  
 {4, 5, 6, 7} ,  
 {8, 9, 10, 11} 
};

//jagged
int[][] sample = new int[2][]{new int[]{1,2,5},new int[]{85,69,87,88}};

Now that we have arrays that can store information, we need to know how to retrieve it. It is identical to how you would be putting information in an array, but in the opposite direction. Refer to the section above. In most cases it is the array identifier followed by the index. Usually you would store this in a variable like the following:

int[] sample = new int[]  {9, 45};
int printThisNumber = sample[1];
Console.WriteLine(printThisNumber);

//the console will output 45. We retrieved it by setting a variable to sample[1]. 

To retrieve a whole section of code we can use a for loop, that loops through the array. Or we can use a foreach loop, as thought by the previous lesson. Here is an example just in case:

//foreach
int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
foreach (int i in numbers)
{
   System.Console.WriteLine(i);
}

//this works on multidimensional arrays too!
int[,] numbers = new int[3, 2] {{9, 99}, {3, 33}, {5, 55}};
foreach(int i in numbers)
{
   Console.Write("{0} ", i);
}

// output of the multidimensional array:
// 9 99 3 33 5 55
// however you may want to use multiple nested for loops instead for more 
// control instead of just retrieving all the info in the 
// multidimensional array


//and normal for loops:
int[] numbers = {4, 5, 6, 1, 2, 3, -2, -1, 0};
for (int i = 0; i < numbers.Length; i++)
	{
	    int consolePrintVariable = numbers [i];
	    Console.WriteLine(consolePrintVariable);
	}

So here are some few more facts about arrays in C#. Arrays in C# cannot not be resized after they are initialized. That mean you cannot add, insert or remove indexes. However you can copy and array, change it, and put it back into a different array. Second, arrays are objects, so they have build in variables and functions. One of the property is the .Length, and it returns how long the array is. Also, it is recommended to use a foreach loop instead of a for loop, since it is simpler, and less mistakes will be made.

Links to tutorials and further reading:
http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx
http://www.tutorialspoint.com/csharp/csharp_arrays.htm

Next up is collections. This is the new, radical way of storing information and is an alternative to arrays. Collections are specialized classes (objects) for data retrieval and storage. In C# there are two main collection classes and a few other minor collections. The first is the ArrayList and the second is List. The minor ones that we will not be going into detail are Hashtable, SortedList, Stack, Queue, and BitArray.

List and ArrayList

ArrayList represents collections of objects that can be indexed individually. They are the collections alternative to Arrays, and have array like features. That means every single thing in the ArrayList collection has an index, similar to arrays. However, ArrayList are like Arrays on steroids, as you can add, remove, and insert into an ArrayList and it will automatically resize the collection. It also has automatic memory allocation, and cool features like sorting, searching, advanced index information, and much more. ArrayLists also have some useful methods/functions built in.

However, ArrayLists are still considered old school, and it is recommended to use List instead. The reason is that ArrayList is its own class type, is specific, and sometimes can’t be mixed with certain types (string, int, double, etc). Also, ArrayList is an array like class, and might have difficulty with certain types. However, List is generic, and is considered type safe, meaning you can use it with any types! The only time you will need to use ArrayList is when there are ArrayList specific functions that are not in the generic List.

To declare and initialize a List do the following:
Remember to using the System.Collections.Generic! It should be automatically be imported by default

using System.Collections.Generic;
List<type> list = new List<type>();

//so a list for int will be:
List<int> list = new List<int>();

//and to add to a list you will use the add method like this:
list.Add(2);

Here is a full example of a Add, and a list print using the foreach loop.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace arrays
{
class Program
{
static void Main(string[] args)
{
List listName = new List();
listName.Add(2);
listName.Add(125362);
listName.Add(225);

foreach (int getNumber in listName) // Loop through List with foreach
{
Console.WriteLine(getNumber);
}
Console.ReadKey();
}

}
}

You can retrieve indexes by using the same method as an normal array. Eg. listName[2];
If you want to see all the List functions and properties, make a List (like listName) above, press “.” and take a look at the intellisense box to see what functions there are. Here are some common functions:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> listName = new List<string>();
            listName.Add("Rito");
            listName.Add("OP");
            listName.Add("kalista");
            listName.Add("thresh");
            //just normal
            foreach (string getNumber in listName) // Loop through List with foreach
            {
                Console.WriteLine(getNumber);
            }

            //spacer in console, pls ingnore
            Console.WriteLine("");

            //a sort (Usullay alphabetical, etc.
            listName.Sort();
            foreach (string getNumber in listName) // Loop through List with foreach
            {
                Console.WriteLine(getNumber);
            }
            //spacer in console, pls ingnore
            Console.WriteLine("");

            // a count of how many
            int howMany = listName.Count();
            Console.WriteLine("There is {0} elements", howMany);

            //finding stuff in an List using a Contains
            bool opExists = listName.Contains("OP");
            if (opExists) 
            {
                Console.WriteLine("Kalista is OP because people suck at countering");
            }
            else
            {
                Console.WriteLine("Kalista is not OP!");
            }

            //you can also find the index number of something using IndexOf
            int indexofOP = listName.IndexOf("OP");
            Console.WriteLine("Index of OP is at {0}", indexofOP);

            //spacer in console, pls ingnore
            Console.WriteLine("");

            //you can insert into an List
            listName.Insert(2, "New Inserted");
            foreach (string getNumber in listName) // Loop through List with foreach
            {
                Console.WriteLine(getNumber);
            }

            Console.ReadKey();
            //there is much more!
        }
    }
}

There are many more. I want you to now go online and find one that I didn’t mention in the example above that is useful. Here are some sites that you can check out:
http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx
http://www.dotnetperls.com/list
http://csharp.net-informations.com/collection/list.htm

Other Collections:

Class Description and Useage
Hashtable It uses a key to access the elements in the collection.

A hash table is used when you need to access elements by using key, and you can identify a useful key value. Each item in the hash table has a key/value pair. The key is used to access the items in the collection.

SortedList It uses a key as well as an index to access the items in a list.

A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key , it is a Hashtable. The collection of items is always sorted by the key value.

Stack It represents a last-in, first out collection of object.

It is used when you need a last-in, first-out access of items. When you add an item in the list, it is called pushing the item and when you remove it, it is calledpopping the item.

Queue It represents a first-in, first out collection of object.It is used when you need a first-in, first-out access of items. When you add an item in the list, it is called enqueue and when you remove an item, it is calleddeque.
BitArray It represents an array of the binary representation using the values 1 and 0.

It is used when you need to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index, which starts from zero.

Lesson 4: Loops

Loops are for running sections of code multiple times. Loops in C# are extremely similar to Java, and most programming languages in general. Double check your brackets! This is very useful for creating or changing a lot of things at once. There are four main ways to loop. Remember the loop is considered 1 statement, so no need to end with a semicolon(EXCEPT FOR DO WHILE!) and make sure the brackets enclose all the code inside.

  1. While loop
  2. for loop
  3. do while loop
  4. foreach

The while loop is the most basic loop. If a boolean condition is met, it will loop through the code. They key thing is that the condition is tested before the loop starts. Here is an example:

 class Program
    {
        static void Main() 
        {
            int n = 1;
            while (n < 6) 
            {
                Console.WriteLine("Current value of n is {0}", n);
                n++;
            }
        }
    }

The next loop is the For loop.
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.

The for loop is in the following format:

for ( init; condition; increment )
{
   statement(s);
}

Here is an example that will count from 0 – 10. As you can see, it starts from variable a, that is at 0, and it will loop until it is 10, and each loop it adds up by 1.

namespace loops
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int a = 0; a <= 10; a= a + 1)
            {
                Console.WriteLine("value of a: {0}", a);
            }
            Console.ReadKey();
        }
    }
}

Lastly there is do while loops. Do while are loops are identical to while loops, except that the code is ran once before the loop condition is checked. Remember it runs once no matter what.
Do while is in the following style:

do
{
   statement(s);

}while( condition );

And here is an example. Notice how it outputs “Rito Plz” no matter what. Try and change the variables to true and false to see how the do while works. Do while do end in a semicolon.

namespace loops
{
    class Program
    {
        static void Main(string[] args)
        {
            Boolean serversUp = false;
            do
            {
                Console.WriteLine("Rito Plz");
            } while (serversUp);

        }
    }
}

and here is a more advanced example:

namespace Loops
{
    
    class Program
    {
        static void Main(string[] args)
        {
            int a = 10;
            do
            {
               Console.WriteLine("value of a: {0}", a);
                a = a + 1;
            } while (a < 20);

            Console.ReadLine();
        }
    }
} 

Lastly there is the foreach loop. It is similar to Java’s enhanced for in loop. This loop is useful for looping through arrays/collections. In java it is:

for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }

in C# it is:

foreach (string name in names)
{
Console.WriteLine(name);
Console.WriteLine(",");
}

Here is a full example:

    static void Main(string[] args)
    {
        int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
        foreach (int element in fibarray)
        {
            Console.WriteLine(element);
        }
        Console.WriteLine();


        // This is the above loop in a traditional for loop. Notice how it is simpler.
        for (int i = 0; i < fibarray.Length; i++)
        {
            Console.WriteLine(fibarray[i]);
        }
        Console.WriteLine();


        // You can maintain a count of the elements in the collection/array. 
        int count = 0;
        foreach (int element in fibarray)
        {
            count += 1;
            Console.WriteLine("Element #{0}: {1}", count, element);
        }
        Console.WriteLine("Number of elements in the array: {0}", count);
        Console.ReadKey();
    }
    // Output: 
    // 0 
    // 1 
    // 1 
    // 2 
    // 3 
    // 5 
    // 8 
    // 13 

    // 0 
    // 1 
    // 1 
    // 2 
    // 3 
    // 5 
    // 8 
    // 13 

    // Element #1: 0 
    // Element #2: 1 
    // Element #3: 1 
    // Element #4: 2 
    // Element #5: 3 
    // Element #6: 5 
    // Element #7: 8 
    // Element #8: 13 
    // Number of elements in the array: 8
}

In loops there are key words or statements. They include break, continue, and goto. Break immediately ends the loop and exits out of it. Continue instantly jumps to the next iteration of the loop. In most cases this is the beginning of the loop. Goto goes to a label or a case. For example

goto cool;

will go to somewhere labeled:

cool:

See more here:
http://www.tutorialspoint.com/csharp/csharp_loops.htm
http://msdn.microsoft.com/en-us/library/f0e10e56%28v=vs.90%29.aspx

Lesson 3: Conditional Logic

In C# it isn’t really different from languages like Java. In this case, the conditional logic is almost identical.

The first one, the If statements. An if statement consists of a boolean expression followed by one or more statements.
Here is an example:

namespace logic
{
    class Program
    {
        static void Main(string[] args)
        {
            String franklinisawesome = "yes";
            if (franklinisawesome == "yes")
                {
                    Console.WriteLine("Franklin is the bomb");
                }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}

In this case, the code will output Franklin is the bomb, since franklinisawesome is equal to yes.

The next one is If Else statement. An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
Here is the example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace logic
{
    class Program
    {
        static void Main(string[] args)
        {
            String franklinisawesome = "No";
            if (franklinisawesome == "yes")
            {
                Console.WriteLine("Franklin is the bomb");
            }
            else
            {
                Console.WriteLine("awww. =(");
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}

in this case, it will output awwww. =( because franklinisawesome is not true, therefore the else statement is ran instead.

Lastly there is switch statement. A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
Here is the example:

class SwitchTest
{
    static void Main()
    {
        Console.WriteLine("Coffee sizes: 1=small 2=medium 3=large");
        Console.Write("Please enter your selection: ");
        string str = Console.ReadLine();
        int cost = 0;

        // Notice the goto statements in cases 2 and 3. The base cost of 25
        // cents is added to the additional cost for the medium and large sizes.
        switch (str)
        {
            case "1":
            case "small":
                cost += 25;
                break;
            case "2":
            case "medium":
                cost += 25;
                goto case "1";
            case "3":
            case "large":
                cost += 50;
                goto case "1";
            default:
                Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
                break;
        }
        if (cost != 0)
        {
            Console.WriteLine("Please insert {0} cents.", cost);
        }
        Console.WriteLine("Thank you for your business.");
    }
}
/*
    Sample Input: 2

    Sample Output:
    Coffee sizes: 1=small 2=medium 3=large
    Please enter your selection: 2
    Please insert 50 cents.
    Thank you for your business.
*/

Of course there is nested statements, which mean you can stack multiple elses or switches inside each other, etc.
For more information, visit:

http://msdn.microsoft.com/en-us/library/676s4xab.aspx
http://www.tutorialspoint.com/csharp/csharp_decision_making.htm

Lesson 2: Variables

Alright, now that we have the basics down, we are moving on to variables. In C# there are multiple types of variables.  Here are the general types of variables listed below in the chart.

Type Example
Integral (numbers) types sbyte, byte, short, ushort, int, uint, long, ulong and char
Floating (representing numbers approximately) point types float and double
Decimal types decimal
Boolean types true or false values, as assigned
Nullable types Nullable data types

 

In general C# variables follow this format:

<data_type> <variable_list>;

 In C# you do not need to initialize your variables when you declare them. For example:

 
//these are valid variable declaration.
int i, j, k;
char c, ch;
float f, salary;
double d;

//however if you want to initialize them you can. Like this:
int i = 100;

//here are more initialization:
int d = 3, f = 5;    /* initializing d and f. */
byte z = 22;         /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x';        /* the variable x has the value 'x'. */

Now that we know about the variables, here is the example code that explores variables.

namespace Variables
{
    class Program
    {
        static void Main(string[] args)
        {
            short a;
            int b ;
            double c;

            /* actual initialization */
            a = 10;
            b = 20;
            c = a + b;
            Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
            Console.ReadLine();
        }
    }
}

This code should produce the following:

a = 10, b = 20, c = 30

If you want to read from the console, you can use the following:

 
Console.ReadLine();

//and to use it to get an integer:
int num;
num = Convert.ToInt32(Console.ReadLine());

Lesson 1: Hello World

Welcome to the first lesson in our adventure in C# (C Sharp).

We will be creating a traditional first time  program, called the hello world program. This program will allow to explore C# and Visual studio, and is one of the simplest programs.

First we need to setup Visual studio to create our program. The type of program we are making today is a Console Application, which is a application that doesn’t have a GUI and is only a console (Command Prompt/CMD thing).

Under start hit the New Project link

l1i1

A window should pop up. Click on Templates from the list on the left. Under Templates, click on Visual C#. You’ll then see Console Application appear in the middle. Name your project accordingly, and save it somewhere safe. You will be storing your other projects in the same place. Press OK.l1i2

Your screen should now look something like the picture below. There should be some code already in place. If you notice on the right hand side, there is a solution explorer.  This is like a file explorer for your project. This is the area where you would find all your code, libraries, and related files.

Properties are the setting for your project, where stuff like versions, author, etc. is located at.

References are the files and pieces of code that your code is referencing. This is usually a library or code that someone else wrote, and in this case, it is code that is built into C#.

Program.cs is the file you are programing your  code.

On the left hand side is the main window. This is where you will be programming your code.

l1i3

Now that we are setup, we are going to look at our code. The using  is equivalent to import in Java. It tells the program to import libraries of code during, and is using the code further on in the program.

Namespace is like the package in Java. A namespace is what it infers, a space where names can be in. In programming you cannot reuse names in a program, but namespaces only make it so you cannot reuse names inside the namespace, allowing the same name used in multiple locations.

Class is where you define you define your object, giving it a name. If you can recall, a class/object is like a car, it can have different properties (Variables like colour, trim, etc) and different functions/methods (like drive forward, backwards, etc).

The following piece of code is the the main method. The static means that the function can be run without context, or in a new object. The void means that the function does not return, or send anything back, to the code that requested it. The Main is the name, and the string[] args is the command line arguments that can be given to the program at startup.

static void Main(string[] args)

Now, we will write our first line of code. Here it is:

Console.WriteLine("Hello World");

When you are typing this you may notice a box popping up. This is intelleSense. It auto completes your code, and gives you tips and information.

l1i4

Now hit the start button up top. Notice how there is a debug drop down menu. You can change this to production release, if you are using the advanced debug features in the future.

When you run it, you may noticed that the program closes right away. This is normal, because the code has reach the end, so it closes itself. However, this means you can’t see what is going on. So we insert the following code:

Console.WriteLine("Press any key to continue...");
Console.ReadKey();

This writes the Press any key to continue… to the console. The ReadKey method then waits for a key to be pressed. Since there is no code left, it exits the program.

Congratulations, you finished your first C# program.

Also, if you need help with code, C# is a microsoft created programming language. That means they have one of the best reference resources out there, and examples for almost everything. Check it out: http://msdn.microsoft.com/en-us/library/kx37x362.aspx

GG WP. NO RE. GIT GUD SKRUB.

The whole code is below and you can download it here.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}