About this Tutorial

Objectives

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

  • Use Visual Studio 2012 effectively
  • Create commercial C# Web Applications
  • Develop multi-threaded applications, Use WCF and LINQ

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 C# will also find the content beneficial.

Prerequisites

No previous experience in C# programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Download Solutions

HTML tutorial


Overview
In this tutorial we will be showing you the core features that are present in the C# programming language. This will range from variables and operators to using loops in programs, for the people who have had some programming experience the C# language is very similar to Java and in learning this you will be learning the key concepts of Java at the same time.

Estimated Time – 1 Hour

Not what you are looking? Try the next tutorial – Defining Types

Lab 1: Language Essentials

Lab 1: Language Essentials
  1. Anatomy of a simple program -The most simple type of program in .NET is a console application.
    • Define a class.
    • Implement a static Main() method.
    • Optionally declare an array of strings as input to Main().
    • Optionally return an int from Main().
    • namespace HelloWorldApp
      {
       class Program
       {
        static int Main(string[] args)
        {
         Console.WriteLine("Thanks for passing in {0} arguments!", args.Length);
         return 0;
        }
       }
      }

  2. Variables
    • All programs use variables- you must initialize the variables before you use them.
    • type variableName = optional-initial-value; // Syntax
      int yearsToRetirement = 20; // Example

  3. Constants – fixed variables, cannot be changed. Below is a table of keywords for variables consisting of their descriptions and ranges where each of them may be best suited to a specific purpose.
      const type constantName = mandatory-compile-time-constant-value; // Syntax
      const double PI = 3.1415; // Example
  4. CommonlyUsed

    Lab
  1. Using the Console Class – Class permits simple console I/O.
    • Console.Write()
    • Console.WriteLine()
    • Console.ReadLine()
    • Use {0} etc. as placeholders in output string, you can use formatters to format output e.g.{0:c}. for {d8} it will be to 8 places and for {f4} it will have 4 places after the floating point.
    • ConsoleClass

  2. View code file.
  3. Using the String Class
    • String class represent a unicode character string – String literal have the format “xxx”; they are able to contain escape characters e.g. \n and to prevent the character expansion, prefix string literal with @.
    • Useful Properties/methods
      • Length.
      • Compare(), contains(), Equals(), Format() etc…
      • String objects are immutable – you can’t change them, if you need to change them use StringBuilder.
      • StringClass

    • View code file.

Lab 2: Operators

Lab 2: Operators
  1. Arithmetic Operators – A symbol that takes an action
    • Basic Binary OperatorsTakes 2 operands (% is the modulus symbol that returns a remainder e.g. 10 mod 3 = 1):
      • a + b
      • a – b
      • a * b
      • a / b
      • a % b
    • Basic unary operators – Takes one operand, the difference between a++ and ++a is when using the value for a++ it uses the value of a and then increments a afterwards; whereas for ++a it increments a and then uses its value:
      • +a
      • -a
      • a++
      • a–
      • –a
  2. Conditional Operator – It is like an in-situ if test e.g. (condition) ? trueResult : falseResult.
    bool isMale; // boolean value either true or false
    int age;
    ...
    int togo = (isMale) ? (65 - age) : (60 - age); // if it is a man use 65 otherwise use 60
    Console.WriteLine("You have {0} years to go to retirement.", togo);
  3. Assignment Operators – Basic assignment operator, a = b, Performs widening conversion implicitly.
    • For value types e.g. integers – Assign LHS variable a copy of RHS values.
      int a = 100;
      int b = 200;
      b = 42; // b is now 42.
      a = b; // a is now 42.
    • For reference types e.g. classes – Assign LHS variable a reference to RHS object.
      Person p1 = new Person("John", "Developer", 25000);
      Person p2;
      p2 = p1; // p2 points to same Person object as p1.
  4. Compound assignment operators – for a quick example a+=b means a = a + b and is just a quicker way of helping the programmer in creating an application:
    • a += b
    • a -= b
    • a *= b
    • a /= b
    • // Use *= compound operator:
      x *= a + b;
      // Equivalent to the following (note the precedence):
      x = x * (a + b);

  5. String Concatenation – you can conjoin string using the + operator but remember if you are using words to leave ” ” (spaces) between them. Strings can be seen as anything held in “” commas that can also have variables put between them e.g. “hello you are ” + age + ” years old”:
    • strResult = str1 + str2
    • strResult = str1 + obj
    • Using shortcut concatenation – str1 += str2.
    • String message = "Hello";
      int a = 5;
      int b = 6;
      Console.WriteLine(message + a + b);
      Console.WriteLine(message + (a + b));
      Console.WriteLine("" + a + b);
      Console.WriteLine(a + b);

  6. Casting:
    • Implicit – Converts less-precise to more-precise e.g. byte > short > int.
    • Explicit – Conversions aka casting – (type) expression; might result in a loss of precision.
      int judge1Score;
      int judge2Score;
      int judge3Score;
      ...
      double averageScore = (double) (judge1Score + judge2Score + judge3Score) / 3;
  7. Relational Operators – 6 relational operators:
    • ==
    • !=
    • >
    • >=
    • <
    • <=
  8. Comparing Values
    • By using == or != on value types e.g. integers; you are comparing numeric types.
    • If you use == or != on reference-types objects; you are comparing object references, if you want to compare values use the Equals() method.
  9. Logical Operators:
    • && – Logical AND
    • || – Logical OR
    • ! – Logical NOT
  10. Bitwise AND/OR/NOT and shift operators:
    • & – bitwise AND
    • ^ – bitwise OR
    • | – bitwise inclusive OR
    • ~ – bitwise NOT
    • << – shift bits left
    • >> – shift bits right

Lab 3: Conditional Statements

Lab 3: Conditional Statements
  1. Using if Tests:
    • Basic if tests, tests the condition and if it is true will run the code in the body.
      if (booleanTest) {
       body
      }
    • If

    • if-else tests, if it is true it will run the code in the body otherwise it will move to the else and run the code in the else body. This means we now have code for both true and false.
      if (booleanTest) {
       body1
      } else {
       body2
      }
    • ifelse

    • if-else-if tests, this will test a condition and if it is true will do that code in the body otherwise it moves its way down the if statement to the next else if and tests that condition etc… if none of the conditions were true the else at the end will run its body code.
      if (booleanTest1) {
       body1
      }
      else if (booleanTest2) {
       body2
      }
      else if (test3) {
       body3
      }
      ...
      else {
       lastBody
      }
    • Nesting if Tests, this is where you have an if statement inside an if statement and this can go on for many levels and without properly indented code can become very hard to understand.
      int age = ...;
      String gender = ...;
      if (age = 100) {
        Console.WriteLine("centurion ");
       }
       if (gender == "Male") {
        Console.WriteLine("man");
       } else {
        Console.WriteLine("woman");
       }
      }
    • nested

  2. Using switch Tests – switch statements is useful if you want to test a single expression against a finite set of expected values.
    switch (expression) {
    case constant1:
     branch1Statements;
     break;
    case constant2:
     branch2Statements;
     break;
    ...
    default:
     defaultBranchStatements;
     break;
    }

Lab 4: Loops

Lab 4: Loops
  1. Using while loops:
    • The while loop is the most straightforward loop construct.
    • Boolean test is evaluated.
    • If true, loop body is executed.
    • Boolean test is re-evaluated.
    • Loop body will not be executed if test is false initially.
    • while (booleanTest) {
       loopBody
      }

      while

  2. Using do-while loops:
    • The do-while loop has its test at the end of the loop.
    • Loop body is always evaluated.
    • Handy for input validation.
    • Note the trailing semicolon.
    • do {
       loopBody
      } while (booleanTest);

  3. dowhile

  4. Using for loops:
    • The for loop is the most explicit loop construct.
    • Initialization part can declare/initialize variables.
    • Test part can have as many tests as is needed.
    • Update part can do anything.
    • for (init; booleanTest; update) {
       loopBody
      }

  5. Using foreach loops:
    • The foreach loop iterates through an array or collection.
    • Iterate through an array of integers
      int[] examMarks = { 75, 85, 92, 71, 99 };
      foreach (int m in examMarks)
      {
       Console.WriteLine("Mark: {0}", m);
      }
    • Iterate through a collection of strings –
      List favouriteCities = new List();
      ...
      foreach (string c in favouriteCities)
      {
       Console.WriteLine("City: {0}", c);
      }
  6. Unconditional jumps:
    • Sometimes it can be convenient to use unconditional jump statements within a loop.
    • break – terminates innermost loop.
    • continue – terminates current iteration and starts next iteration.
    • return – terminates entire method.
    • for (initialization; test; update) {
       ...
       if (someCondition)
      break;
       ...
       if (someOtherCondition)
      continue;
       ...
      }

 

Well done. You have completed the tutorial in the C# course. The next tutorial is

3. Defining Types


Back to beginning
Copyright © 2016 TalkIT®






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