11. Additional C# Language Features

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
Object initializers let you assign values of an object when you are creating them without the need to invoke a constructor with assignment statements after this. The object initializer syntax allows you to choose what arguments you send in for an object. Anonymous types enable the select clause in a LINQ query expression to transform objects of the original sequence into objects whose value and shape may differ from the original. This is useful if you want to store only a part of the information from each object in a sequence.

Estimated Time – 1 Hour

Not what you are looking? Try the next tutorial – LINQ to Objects

Lab 1: Object and Collection Initialization

Lab 1: Object and Collection Initialization
  1. Object initialization Syntax:
    • You can initialize an object’s properties directly, during object creation:
      • Create object using new, as usual.
      • Optionally pass parameters into a constructor.
      • Then use {} to enclose property=value expressions, separated by commas.
    • Popular technique amongst C# developers:
      • Obviates the need for multiple constructors.
      • Client code can just set the properties it wants to.
  2. Collection Initialization Syntax:
    • You can initialize a collection directly, during collection creation:
      • Similar idea to object initialization syntax.
      • Create collection using new, as usual.
      • Then use {} to enclose collection items.
    • Populartechnique amongst C# developers:
      • Obviates the need to call Add() to add items to collection manually.
Lab
    1. To help demonstrate the use of initializing a collection we will use a solution that has been pre-made that we will then modify to show this in action. This solution will also be used in the next labs; the solution is called BankSystemInitial and can be downloaded from the top of the page.
    2. Once this is opened you should see one solution that contains 4 class files. For this lab we only need to edit program.cs and the method labelled exercise one
    3. What we are going to do is using the BankAccount class to create some new bank accounts. Some normally using object initializer syntax and some using collection initializer syntax
      private static void Exercise1Test()
      {
      ...
      // Create some objects using object initializer syntax.
      BankAccount acc1 = new BankAccount { AccountHolder = "John", Balance = 1000 };
      ...
      // Create a collection using collection initializer syntax.
      List<BankAccount> accounts = new List<BankAccount>
      {
      new BankAccount { AccountHolder = "Huey", Balance = 4000 },
      ...
      };
      foreach (BankAccount acc in accounts)
      ...
      }
    4. View code file.

      • On running the application you should see the following results showing all the accounts in the collection that we made –
        feature

Lab 2: Anonymous Types

Lab 2: Anonymous Types

Overview

  1. An anonymous type is a type that has no name:
    • OK, you could have probably guessed this yourself!
  2. This is how anonymous types work:
    • Create an object using new, but omit the type name:
      • Just enclose property setters in {}.
      • The compiler generates a type name internally.
    • Assign the object to a var variable:
      • You must use var, because you don’t know the type name!
  3. Purpose of Anonymous Types:
    • Anonymous types are primarily used in LINQ (Language Integrated Queries):
      • See later in course.
    • In a nutshell:
      • You can use LINQ to query a data source (such as a collection, or an XML document, or a database).
      • If you don’t want to see the entire result for each “row” in the result set, you can use an anonymous type.
      • The anonymous type specifies the subset of data you want back.
Lab
  1. Carrying on from lab one, we will be using the same application and will be editing program.cs but this time we will use exercise two.
  2. we are going to create a bank and fill it with some bank accounts and then we will create an anonymous type that allows us to hold what data we want know about for our bank.
  3. In exercise two add the following code. The main point of the code is to look at the var info and the information that it is holding and how we can access this information through info –
    private static void Exercise2Test()
    {
    ...
    // Create a Bank and add some BankAccounts.
    Bank bank = new Bank();
    bank[123] = new BankAccount { AccountHolder = "John", Balance = 1000 };
    ...
    // Create an object of anonymous type.
    var info = new { NumAccs = bank.NumberOfAccounts, LastAccBalance = bank[789].Balance, Timestamp = DateTime.Now };
    // Display values of object of anonymous type.
    Console.WriteLine("Number of accounts: {0}", info.NumAccs);
    ...
    }
  4. View code file.
  5. The end result should look something like this assuming you don’t comment out exercise one. As you can see it is printing all the expected results but what is cool is the getType() method as it is a jumble of different types
    feature

Lab 3: Extension Methods

Lab 3: Extension Methods

Overview

  1. You can augment an existing type (e.g. class, structure, or interface) with extension methods:
    • Create an object using new, but omit the type name.
  2. Extension methods must be defined in a static class:
    • An extension method is a static method.
    • … where the first parameter is prefixed with this.
    • … to indicate the type of object that it extends.
  3. Client code uses the method seamlessly:
    • Just like any regular instance method.
  4. Uses of Extension Methods:
    • Extension methods are primarily used in LINQ:
      • See later in course.
    • In a nutshell:
      • You can use LINQ to query a data source (such as a collection, or an XML document, or a database).
      • LINQ queries resolve to IEnumerable or similar, which have many new extension methods.
      • E.g. Where(), First(), Sum(), Average(), etc…
Lab
  1. For this lab we are going to create something a little more substantial compared to the other two. Open the solution we have been working on through the last two labs.
  2. we are going to create some extension methods that could be used by a bank system such as password strength. To start create a new class library by clicking File>Add>New Project and choose Class Library and call this MyExtensionLibrary
    HelpAdd feature
  3. Now in MyExtensionLibrary add a new class called MyExtension and add the following two methods that must be static. First one is a range check that checks to see if a number is in a range of numbers –
    public static bool InRange(this double number, double min, double max)
    {
    return number >= min && number <= max;
    }
  4. The second method checks to see if a password is strong by seeing if it contains digits and non alphanumeric characters and is over 8 characters
    public static bool IsStrongPassword(this string str)
    {
    if (str.Length < 8)
    return false;
    ...
    foreach (char c in str)
    {
    if (char.IsDigit(c))
    ...
    if (digitFound && nonAlphanumericFound)
    return true;
    }
    // If we get this far, the string is weak password.
    return false;
    }
  5. View code file.
  6. Now to add the client code but first we need to reference this into our BankSystem by right clicking on references in BankSystem Add Reference>Solution and then ticking the MyExtensionLibrary box. Then you just need to add a using statement in program.cs at the top of the page –
    HelpRef
    using MyExtensionLibrary;
  7. The last thing to do is to add our code to exercise three to test this all. It will ask for user input for a number and check this to see if it is on range and then a string and see this as a password in terms of strength –
    private static void Exercise3Test()
    {
    ...
    Console.Write("Enter a number: ");
    double num = double.Parse(Console.ReadLine());
    if (num.InRange(10, 30))
    ...
    Console.Write("Enter a string: ");
    string str = Console.ReadLine();
    if (str.IsStrongPassword())
    ...
    }
  8. View code file.
  9. The end result should look something like this –
    app3

 

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

12. LINQ to Objects


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