Programming with C# using Visual Studio 2010

About this Tutorial –

Objectives –

Delegates will learn to develop web applications using C# 4.0. After completing this course, delegates will be able to:

  • Use Visual Studio 2010 effectively
  • Programming with C# using Visual Studio 2010

Audience

This course has been designed primarily for programmers new to the .Net development platform. Delegates experience solely in Windows application development or earlier versions of ASP.Net will also find the content beneficial.

Prerequisites

Before attending this workshop, students must:

  • Be able to manage a solution environment using the Visual Studio 2010 IDE and tools
  • Be able to program an application using a .NET Framework 4.0 compliant language

Contents

Copyright 20/12/12 – David Ringsell

Download Solutions

Java tutorial

Lab 1 – C# Language Fundamentals

In this lab we will start to work with C#. We will do this by creating Console Applications in Visual Studio. Then write statements that prompt and greet the user.

  1. Open Visual Studio 2010 and create a new C# Console Application:
    • Select the File menu, then New, then Project.
    • Make sure that Visual C# and then Windows is selected at the left of the screen
      under Installed Templates.
    • Name the project and the solution: CSharpLanguageFundamentals.
    • Browse to the place on your computer where you wish Visual Studio
      to create the directory for your solution (keeping the tick box selected).
    • Select Console Application and then click OK.
  2. In Program.cs find the Main method and insert the following line:
    string myName;
  3. Write a statement that prompts users for their name.
  4. Write another statement that reads the user’s response from the keyboard and assigns it to the myName string.
  5. Add one more statement that prints “Hello myName” to the screen (where myName is the name the user typed in).
  6. When completed, the Main method should contain the following:
    static void Main(string[ ] args).
    {
       string myName;
       Console.WriteLine("Please enter your name");
       myName = Console.ReadLine( );
       Console.WriteLine("Hello {0}", myName);
    }
  7. Test the application and save your work.
  8. View code file

Lab 2 – Branching
Create a Console Application that uses conditional and branching statements. Complete three simple programming tasks in C#.

  1. Open Visual Studio and create a new C# Console Application.
  2. Write statements to input two positive integers and display the sum.
    static void Main(string[] args)
    {
       try
       {
          int valueOne;
          int valueTwo;
          int valueThree;
          System.Console.WriteLine
          ("Please Enter A Whole Number: ");
          valueOne = int.Parse(Console.ReadLine());
          System.Console.WriteLine
          ("Please Enter Another Whole Number: ");
          valueTwo = int.Parse(Console.ReadLine());
          valueThree = valueOne + valueTwo;
          if (valueThree > 0)
          {
             System.Console.WriteLine
             ("The Sum of ValueOne: {0} and ValueTwo: {1} is Equal
             to: {2}", valueOne, valueTwo, valueThree);
          }
          else
          {
             System.Console.WriteLine
             ("Both Values were Zero!");
          } // End if
       } // End try block
       // Handle exception generated by user input entered in
       // the wrong format
       catch (System.FormatException)
       {
          Console.WriteLine(
          "You didn't enter a Whole Number!");
       }
       Console.WriteLine(
       'n' + "Please Press any Key to Exit");
       System.Console.ReadKey();
    } // End main method
  3. View code file
  4. Write statements to input three numbers and display the largest using if statements. Aim to use the minimum number of statements.
    // Compare the numbers to find out which is the highest number
    int intMax = intFirst;
    if (intSecond > intMax) intMax = intSecond;
    if (intThird > intMax) intMax = intThird;
    // Show the largest
    Console.WriteLine("The largest is {0}", intMax);
  5. View code file.
  6. Write a switch statement to input a country and display its capital.
    string myCountry;
    System.Console.WriteLine
    ("Please Enter A Country: ");
    myCountry = Console.ReadLine();
    // Use switch to compare the myCountry string to the choices of country
    switch (myCountry)
    {
       case "England":
          Console.WriteLine("Your Capital is London.n");
          break;
       case "France":
          Console.WriteLine("Your Capital is Paris.n");
          break;
       case "Germany":
          Console.WriteLine("Your Capital is Munich.n");
          break;
       default:
          Console.WriteLine("The Capital is Unknown.n");
          break;
    }
  7. View code file
  8. Write statements that display the sequence 10, 20, 30, 40 … 100. Use a for loop.
    int counter = 1;
    int counterb = 0;
    // Use for loop to generate values from 1 to 100
    for (; counter < 101; counter++)
    {
       // Use another counter variable to count from 1 to 10
       // Print out counter when counterb reaches 10
       counterb++;
       if (counterb == 10)
       {
          Console.WriteLine(
          "counter: {0} ", counter);
          counterb = 0;
       }
    }
  9. View code file.
  10. Write statements that to display the sequence 1, 2, 3, … 100, as 10 rows of 10 numbers. Use a for loop.
    int counterVariable = 0; // initialization
    int nextCounter = 0;
    // A string variable to store the numbers as string values so that they
    // can be printed
    string numberRow = " ";
    // Use for loop to count from 1 to 100
    for (counterVariable = 1; counterVariable < 101; counterVariable++)
    {
       // Use nextCounter variable to count from 1 to 10
       nextCounter++;
       if (counterVariable < 11)
       {
          numberRow += Convert.ToString(counterVariable) + " ";
       }
       else
       {
          numberRow += Convert.ToString(counterVariable) + " ";
       }
       // When nextCounter reaches 10 print out the line of numbers
       if (nextCounter == 10)
       {
          Console.WriteLine(numberRow);
          numberRow = " ";
          nextCounter = 0;
       }
    }
  11. View code file
  12. Test the application and save your work.
  13. When testing this solution make sure you exclude the code (.cs) files you are not running from the project:
    • Make sure you have ‘Show All Files’ selected by clicking the second icon from the left at the top of Solution Explirer.
    • Right-click on each of the .cs files you want to exclude and select Exclude From Project.
    • Right-click on the class file you want to include and select Include In Project. The program will then only execute the code within that file.

Lab 3 – Operators
Create a Console Application that uses arithmetic and logical operators. Complete an arithmetic and a logical programming task.

  1. Open Visual Studio and create a new C# Console Application.
  2. Write statements using the multiplication operator to display the twelve-times table. Enter a number from 1 to 12, then display the number multiplied by 12.
    int valueOne;
    int valueTwo;
    // A const variable to hold the value that each number will be
    // multiplied by
    const int multiplyer = 12;
    Console.WriteLine(
    "Please enter a number between 1 and 12");
    valueOne = int.Parse(Console.ReadLine());
    // Use && operator to determine whether the number entered
    // by the user is between 1 and 12
    if (valueOne > 0 && valueOne < 13)
    {
       valueTwo = valueOne * multiplyer;
       Console.WriteLine(
       valueOne + " x " + multiplyer + " = " + valueTwo);
    }
    else
    {
       Console.WriteLine(
       "You didn't enter a number between 1 and 12");
    }
  3. View code file.
  4. Write statements to input two numbers and use logical operators to output if the result of multiplying them will be positive or negative. For example, a negative number multiplied by a negative number, gives a positive result.
    valueThree = valueOne * valueTwo;
    // Use the && operator to determine whether the two numbers are
    // both positive numbers - more than 0
    if (valueOne > 0 && valueTwo > 0)
    {
       Console.WriteLine(
       "The answer is a Positive Number. The answer is: "
        + valueThree);
    // Use the && operator to determine whether the two numbers are
    // both negative numbers - less than 0
    } else if (valueOne < 0 && valueTwo < 0)
    {
       Console.WriteLine(
       "The answer is a Positive Number. The answer is: " + valueThree);
    }
    // Use the OR operator to determine whether one of the numbers is
    // less than 0
    else if (valueOne < 0 || valueTwo < 0)
    {
       Console.WriteLine(
       "The answer is a Negative Number. The answer is: " + valueThree);
    }
    else
    {
       Console.WriteLine(
       "Both numbers are not greater or less than 0");
    }
  5. Test the application and save your work.
  6. View code file.

Lab 4 – Debugging
Examine and debug your C# code by using Visual Studio’s debugging features. These in include pausing code at a breakpoint, stepping through statements and using the debug windows.
For all remaining lab exercises throughout this course, examine and debug your code by:

  1. Setting breakpoints in lines of code by clicking in the margin. When run the code will pause at the first beakpoint.
  2. Stepping through lines of code when a breakpoint is hit by pressing F11. The code will execute line by line. Hover the mouse pointer over a variable to show its current value.
  3. Using these debug windows to understand and fix code:
    • Watch
    • Locals
    • Immediate
    • Call Stack
  4. Debug windows are available only when the code is paused in break mode. Use the Debug>Windows command to show them.

Lab 5 – Structs
Create a Structure to hold colour values. Use the Structure in code.

  1. Open Visual Studio and create a new C# Console Application.
  2. Define a struct called Colour, with a constructor and a ToString() method.
  3. Add three integer properties to represent the red, green and blue component of the colour.
    public struct Colour
    {
       public int red { get; set; }
       public int green { get; set; }
       public int blue { get; set; }
       // Constructor
       public Colour(int rVal, int gVal, int bVal) : this()
       {
          red = rVal;
          green = gVal;
          blue = bVal;
       }
       // Display the Struct as a String
       public override string ToString()
       {
          return (String.Format("{0}, {1}, {2}", red, green, blue));
       }
    }
  4. Test the struct.
    // Create an instance of the struct
    Colour colour1 = new Colour(100, 50, 250);
    // Pass the struct to a method
    myFunc(colour1);
    // Display the values in the struct
    Console.WriteLine("colour1 colour: {0}", colour1);
    // Method takes a struct as a parameter
    public void myFunc(Colour col)
    {
       // Modify the values through the properties
       col.red = 200;
       col.green = 100;
       col.blue = 50;
       Console.WriteLine("colour1 colour: {0}", col);
    }
  5. Save your work.
  6. View code file.

Lab 6 – Interfaces
Create an Interface and a Class to hold client details. Instantiate an object from the class in code.

  1. Open Visual Studio and create a new C# Console Application.
  2. Define an interface called IClient.
    // Define the interface interface IClient
  3. Add properties for name and address details and a method called Order(), to the interface.
    void Order(int orderNum);
    string name { get; set; }
    string address { get; set; }
  4. Create a second class called Customer that implements all the interface’s members.
    // Create a Customer class that implements the IClient interface
    public class Customer : IClient
    {
       public Customer(string s)
       {
          Console.WriteLine("Creating a New Customer ID: {0}", s);
       }
       // Implement the Order method
       public void Order(int newOrder)
       {
          Console.WriteLine("Implementing the Order Method for IClient.
          The Order Number is: {0}", newOrder);
       }
       // Implement the properties
       public string name { get; set; }
       public string address { get; set; }
    }
  5. Test the Customer class.
    Customer cust = new Customer("H56388");
    cust.name = "Brian Ferry";
    cust.address = "23 Orange Lane, Clifton, Bristol, BS6 5FH";
    Console.WriteLine("The Name of the Customer is: {0}", cust.name);
    Console.WriteLine("The Address of the Customer is: {0}", cust.address);
    cust.Order(1234);
  6. Test the application and save your work.
  7. View code file.

Lab 7 – Arrays
Create a Console Application that uses a two dimensional array to hold data. Populate the array with integers using a loop.

  1. Open Visual Studio and create a new C# Console Application.
  2. Create a two dimensional array of integers.
    //Declare array
    int[][] intArray;
    //Initialise multi-dimensional array with 10 elements
    intArray = new int[10][];
  3. Use looping statements to populate the array.
    // Populate the int multi-dimensional array using a nested for loop
    for (int j = 0; j < intArray.Length; j++)
    {
       for (int k = 0; k < intArray.Length; k++)
       {
          // The intValue variable will count from 1 to a 100
          // Each of these numbers will be stored in each member
          // of the multi-dimensional array
          intValue++;
          intArray[j][k] = intValue;
          if (intValue < 10)
          {
             // Convert each number to a string and append it to the
             // string variable
             numberRow += Convert.ToString(intArray[j][k]) + " ";
          }
          else
          {
             numberRow += Convert.ToString(intArray[j][k]) + " ";
          }
       }
       // Print out the row of numbers
       Console.WriteLine(numberRow);
       NumberRow = " ";
    }
  4. Test the application and save your work.
  5. View code file.

Lab 8 – Collection Interfaces and Types
Populate an ArrayList, Stack and Queue collections. Then display the values.

  1. Open Visual Studio and create a new C# Console Application.
  2. Create an ArrayList of integers. Use looping statements to populate this with multiples of 10. Print each member of the list. Experiment with the ArrayLists methods, including the Sort(), Reverse() and Clear() methods.
    ArrayList intArray = new ArrayList();
    // Populate the arraylist
    for (int i = 0;i<5;i++)
    {
       intArray.Add(i*10);
    }
    // Print each member of the ArrayList
    foreach (int i in intArray)
    {
       Console.Write("{0} ", i.ToString());
    }
  3. View code file.
  4. Create a Queue of integers. Use looping statements to populate this. Experiment with the Queues methods, including the Dequeue(), Enqueue () and Peek() methods.
    Queue intQueue = new Queue();
    // Populate the Queue
    for (int i = 0;i<5;i++)
    {
       intQueue.Enqueue(i);
    }
  5. View code file
  6. Create a Stack of integers. Use looping statements to populate this. Experiment with the Stacks methods, including the Pop(), Push () and Peek() methods.
    Stack intStack = new Stack();
    // Populate the array
    for (int i = 1;i<5;i++)
    {
       intStack.Push(i);
    }
  7. Test the application and save your work.
  8. View code file.

Lab 9 – Strings
Create a Console Application with strings to hold textual data. Then extract a substring from a string. Also split a string into parts. Finally loop through a array of strings.

  1. Open Visual Studio and create a new C# Console Application.
  2. Input a string representing a URL, e.g. http://www.bbc.co.uk .
  3. Experimenting with extracting substrings, e.g. “bbc”.
    // Create some strings to work with
    string s1 = "http://www.bbc.co.uk";
    string s2;
    string s3;
    int index;
    // Search for first substring
    s2 = s1.Substring( 0, 4);
    Console.WriteLine(s2);
    // Search for next substring
    index = s1.LastIndexOf("/");
    s2 = s1.Substring(index + 1, 3);
    Console.WriteLine(s2);
    // Search for next substring
    index = s1.IndexOf(".");
    s2 = s1.Substring(index+1);
    s3 = s2.Substring(0, 3);
    Console.WriteLine(s3);
  4. View code file.
  5. Experimenting with splitting the URL, e.g. using the dot (.) and forward slash (/) separators.
    // create some strings to work with
    string s1 = "http://www.bbc.co.uk";
    // Constants for the space and comma characters
    const char Space = '/';
    const char Stop = '.';
    const char Colon = ':';
    // Array of delimiters to split the sentence with
    char[] delimiters = new char[]
    {
       Space,
       Stop,
       Colon
    };
    string output = "";
    int ctr = 1;
    // Split the string and then iterate over the
    // resulting array of strings
    String[] resultArray = s1.Split(delimiters);
    foreach (String subString in resultArray)
    {
       if (subString != "")
       {
          output += ctr++;
          output += ": ";
          output += subString;
          output += "n";
       }
    }
    Console.WriteLine(output);
  6. Test the application and save your work.
  7. View code file.

Lab 10 – Throwing and Catching Exceptions
Add exception handling to an application. When an exception (error) occurs the code branches to an exception handler. The handler can then take action to resolve the problem.

  1. Create a console application to enter two integers, then divide the numbers.
    // Do the division if legal
    public double DoDivide(double a, double b)
    {
       if (b == 0)
          throw new System.DivideByZeroException();
       if (a == 0)
          throw new System.ArithmeticException();
          return a / b;
    }
  2. Add exception handling with multiple catch statements.
  3. Catch and respond to division by zero and other exceptions.
    // Most derived exception type first
    catch (System.DivideByZeroException e)
    {
       Console.WriteLine(
       "nDivideByZeroException! Msg: {0}",
       e.Message);
    }
    catch (System.ArithmeticException e)
    {
       Console.WriteLine(
       "nArithmeticException! Msg: {0}",
       e.Message);
    }
    // Generic exception type last
    catch
    {
       Console.WriteLine(
       "Unknown exception caught");
    }
  4. Include a finally statement.
    finally
    {
       Console.WriteLine("Close file here.");
    }
  5. Test the application and save your work.
  6. View code file.

Lab 11 – Delegates
A delegate is a pointer to a method. After declaring a delegate, it can hold any method, providing the number and type of parameters match the delegate’s declaration.

  1. Open Visual Studio and create a new C# Console Application.
  2. Create a class Pair and include a delegate called WhichisFirst, a constructor, and methods called Sort() and ReverseSort().
    // A simple class to hold two items
    public class Pair
    {
       // Private array to hold the two objects
       private object[] thePair = new object[2];
       // The delegate declaration
       public delegate comparison
       WhichIsFirst(object obj1, object obj2);
       // Passed in constructor takes two objects,
       // added in order received
       public Pair(
       object firstObject,
       object secondObject)
       {
          thePair[0] = firstObject;
          thePair[1] = secondObject;
       }
       // Public method that orders the
       // two objects by whatever criteria the objects like!
       public void Sort(
       WhichIsFirst theDelegatedFunc)
       {
          if (theDelegatedFunc(thePair[0], thePair[1])
          == comparison.theSecondComesFirst)
          {
             object temp = thePair[0];
             thePair[0] = thePair[1];
             thePair[1] = temp;
          }
       }
       // Public method that orders the
       // two objects by the reverse of whatever criteria the
       // objects likes!
       public void ReverseSort(
       WhichIsFirst theDelegatedFunc)
       {
          if (theDelegatedFunc(thePair[0], thePair[1]) ==
          comparison.theFirstComesFirst)
          {
             object temp = thePair[0];
             thePair[0] = thePair[1];
             thePair[1] = temp;
          }
       }
    }
  3. The sort methods will take as a parameters an instance of the WhichisFirst delegate.
    // Instantiate the delegate
    Pair.WhichIsFirst theDogDelegate =
    new Pair.WhichIsFirst(
    Dog.WhichDogComesFirst);
    // Sort using the delegate
    dogPair.Sort(theDogDelegate);
    dogPair.ReverseSort(theDogDelegate);
  4. Test the Pair class by creating a Dog class. This implements methods that can be encapsulated by the delegate.
    // Dogs are sorted by weight
    public static comparison WhichDogComesFirst(
    Object o1, Object o2)
    {
       Dog d1 = (Dog)o1;
       Dog d2 = (Dog)o2;
       return d1.weight > d2.weight ?
       comparison.theSecondComesFirst :
       comparison.theFirstComesFirst;
    }
  5. Test the application and save your work.
  6. View code file.

Lab 12 – Generics
Generics allow the type of a parameter to be changed at runtime. This allows the creation of very generalised classes and methods, that can work with any type of data. There are lots of useful predefined generic collections in the .Net framework.

  1. Open Visual Studio and create a new C# Console Application.
  2. Create a class that is generic.
  3. Add generic methods to the class.
    public class Generics<T> // Generic class
    {
       public void Swap<K>(ref K lhs, ref K rhs)
       {
          // Generic method
          K temp;//Local generic data type
          temp = lhs;
          lhs = rhs;
          rhs = temp;
       }
    }
  4. Test the application and save your work.
  5. View code file.

Back to the beginning

If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top