C# 4.0 New Features Using Visual Studio 2010

About this Tutorial –

Objectives –

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

  • Use Visual Studio 2010 effectively
  • Use new features from 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 – Optional Parameters

C# 4.0 New Features - Optional Param's

This enables you to assign a default value to a parameter in a method declaration. When you call the method, you then do not have to pass a value to the parameter. You simply omit parameters you do not use.
It was possible to do something similar before by using overloaded methods. This is clumsy as you have to provide several (overloaded) method declarations.

VB programmers are now laughing as this feature has always been available in VB.Net.

  1. View media clip. Click bottom right of media clip for full screen.
  2. Open Visual Studio.Net and create a new C# Console Application project. Add this code to the Main method.
    static void Process(string data, bool ignoreWS = false, ArrayList moreData = null)
    {
    // Actual work done here
    Console.WriteLine(data);
    }
  3. Then you can call the method with different parameter combinations.
    Process("foo"); //Valid
    Process("foo", true); //Valid
    Process("foo", true, myArrayList); //Valid
    Process("foo", myArrayList); //Invalid
  4. Run the application to test it then save your work.
  5. View code file.

Lab 2 – Named Parameters

The method calls in Lab 1 works fine as long as values are passed to the parameters consecutively, without missing out any intervening values. If a parameter is missed out, the compiler becomes confused as to which value goes to which parameter.

This is where Named Parameters come in useful; these allow you to pass the parameters in any order. Just supply the parameter together with its name in the method call.

  1. View media clip. Click bottom right of media clip for full screen.
  2. Open Visual Studio.Net and create a new C# Console Application project. Add this code to the Main method.
    static void Process(string data, bool ignoreWS = false, ArrayList moreData = null)
    {
    // Actual work done here
    Console.WriteLine(data);
    }
  3. Then you can call the method passing parameters by name.
    Process("foo", moreData: myArrayList); //Valid, MoreData named
    Process("foo", true); //Valid, MoreData omitted
    Process("foo", ignoreWS: true); //Valid, ignoreWS named
  4. Run the application to test it then save your work.
  5. View code file.

Lab 3 – Dynamic Support

When an object is declared as a dynamic type there is no type checking on the object until runtime. Dynamic support comes in very useful when your program is having to interact with objects from other programming environments where the data type is unclear. For example IronPython, JavaScript or COM. The benefits of this will be demonstrated in this tutorial.

  1. View media clip. Click bottom right of media clip for full screen. for full screen.
  2. Open Visual Studio.Net and create a new C# Console Application project. Then to get things started let’s add a Customer class.
    public class Customer
    {
    // properties
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    // Constructor
    public Customer(string strFirstName, string strLastName, int intAge)
    {
    FirstName = strFirstName;
    LastName = strLastName;
    Age = intAge;
    }
    // a method to display the date
    public void DisplayCustomer()
    {
    Console.WriteLine(String.Format("{0} {1} {2}", FirstName, LastName, Age));
    }
    }
  3. Next let’s add an Order class. This has a method GetCustomer that returns a Customer object, but as an Object type.
    public class Order
    {
    Customer cust;
    public Order()
    {
    cust = new Customer("Brian", "Jones", 27);
    }
    //This method returns a Customer but as an Object type
    public Object GetCustomer()
    {
    return cust;
    }
    }
  4. In the Main method create a new Order object, then call its GetCustomer method. Assign the result to a dynamic type. Notice we didn’t have to cast cust to a Customer object.
    Orders ord = new Orders();
    //Declare a dynamic type
    dynamic cust = ord.GetCustomer();
  5. Now lets access some of the members of our returned Customer object.
    cust.FirstName = "Paul"; // works as expected
    cust.DisplayCustomer(); // works as expected
    cust.MissingMethod(); // No method exists but no build error!
  6. Another use of the dynamic type is reuse a variable but change its type. This is a powerful but possibly dangerous feature. Let’s start with declaring an integer, then doing a bit of division. This will cause an error as we cannot implicitly convert from type integer to double.
    int woo = 10;
    woo = woo / 2.5;
  7. This time use a dynamic type and do the division. The runtime now takes care of the type conversion.
    dynamic foo = 10; // This time use a dynamic type
    foo = foo / 2.5;
  8. We can even get away with more dramatic type conversion.
    foo = "John";
  9. Run the application to test it then save your work.
  10. View code file.

Lab 4 – Variance

Variance is the most seeming obscure of the new features. To really get this you need to a good understanding of inheritance and generics. You will probably meet this feature most with generic collections. This tutorial aims to introduce the variance in simple stages.

    1. Open Visual Studio.Net and create a new C# Console Application project. Add this code to the Main method. Let’s get back to basics. Add this code to the Main method.
      String s = "hello";
      Object o = new Object();
    2. Next add these two assignments to the Main method. Do they compile?
      o= s;
      s = o;
    3. Since the String class inherits from the Object class we can assign the String to the Object. But not the other way round. So the first statement compiles, but the second fails.
    4. Lets have some definitions.
      A type system within a programming language can support two kinds of assignment operators – covariant and contravariant .
      The term covariant means that the conversion preserves the ordering hierarchy from the derived , more specific class to the base or generic class. So C# is a covariant language.
    5. Now let’s create two generic Lists with type parameters string and object to the Main method. Then assign one list to the other. Does the assignment compile?
           List<string> strings = new List<string>();
      List<object> objects = new List<object>();
      objects = strings;
    6. You may expect this to compile. After all a string is-an object. But a List of strings is not a List of objects. So it fails. If it did compile then this would work.
      objects.Add(123);
    7. But that would be a problem. We have just inserted an integer into a List<string>.
    8. We may sometimes want to cast the List to any legal type. If the List were read only, we can then view the contents of the List that type.
    9. Let’s try adding elements of the List in different way.
      objects.AddRange(strings);
    10. This does compile. The AddRange method adds the elements of the strings List to the end of objects. It returns a collection of type IEnumerable.
      public interface IEnumerable <out T> : IEnumerable
      {
      IEnumerator<T> GetEnumerator();
      }
    11. The out keyword means IEnumerable is read only. This is new to .Net 4.0. This allows that covariant behaviour.
    12. Let’s take things further to apply the new out key word. Add this generic interface definition directly above the Main method.
      public interface MyInterface<out T>
      {
      T GetItemAt(int index);
      }
    13. Then add this class that implements the interface.
      public class MyClass<T> : MyInterface<T>//Implement interface
      {
      public MyClass(T t1, T t2, T t3)
      {
      _data.Add(t1);
      _data.Add(t2);
      _data.Add(t3);
      }
      public T GetItemAt(int index)//Return item at index
      {//Return item of List at index
      return _data[index];
      }
      //Create List of Ts
      public List<T> _data = new List<T>()
      }
    14. The GetItemAt method returns the item in the List at the specified index.
    15. Next add another class with a method that takes the interface as a parameter.
      public class FooClass<T>
      {
      public static T GetThirdItem(MyInterface<T> foo)
      {
      return foo.GetItemAt(2);
      }
      }
    16. The GetThirdItem method returns the 3rd item in the List passed as a parameter.
    17. In the Main method create two objects using the interface and class definitions. Set the parameter types equal to Object and String.
      MyInterface<Object> myobjects = new MyClass<Object>(1,2,3);
      MyInterface<String> mystrings = new MyClass<String>("a","b","c");
    18. Here T is Object and we are passing an Object version of the class and interface. We would expect this to compile. And it does.
           o = FooClass<Object>.GetThirdItem(myobjects);
    19. Here T is Object but we are passing a String version of the class and interface. This compiles in .Net 4.0 by taking advantage of the out keyword.
           o = FooClass<Object>.GetThirdItem(mystrings);
    20. View code file.

    Lab 5 – COM Interop

    You have probably met .Net applications that work with Word or Excel.
    These applications link to Microsoft Office using COM . .Net 4.0’s support for COM now makes it considerably easier for you to access COM objects from within your .Net applications.

    1. Before .Net 4.0, to open a Word document you would have to write code like something this:
      using Microsoft.Office.Interop;
      using Microsoft.Office.Interop.Word;static void Main(string[] args)
      {
      Object filename = "C:\\My documents\\MyFile.doc";
      Object obj = Missing.Value;
      Object obj2 = Missing.Value;
      Object obj3 = Missing.Value;
      Object obj4 = Missing.Value;
      Object obj5 = Missing.Value;
      Object obj6 = Missing.Value;
      Object obj7 = Missing.Value;
      Object obj8 = Missing.Value;
      Object obj9 = Missing.Value;
      Object obj10 = Missing.Value;
      Object obj11 = Missing.Value;
      Object obj12 = Missing.Value;
      Object obj13 = Missing.Value;
      Object obj14 = Missing.Value;
      Object obj15 = Missing.Value;
      Application wordApp = new Application();
      Document doc = (Document)wordApp.Documents.Open(ref filename, ref obj, ref obj2, ref obj3, ref obj4, ref obj5, ref obj6, ref obj7, ref obj8, ref obj9, ref obj10, ref obj11, ref obj12, ref obj13, ref obj14, ref obj15);
      }
    2. There are two problems with this code. Firstly, this application would includes a reference to the whole interop assembly.
      Interacting with COM objects used to require you to use Primary Interop Assemblies or PIAs; these are large assemblies that demand a huge amount of memory, significantly slowing down the performance of your applications..Net 4.0’s support for COM now only requires that you use the interop code that is necessary for your application.
    3. The other problem with the code in step 1 is the number of parameters you have to pass. They are declared as objects, and then assigned Missing.Value if not used. The parameters then have to be passed by reference.This is no longer necessary in .Net 4.0. The support for optional and named parameters means you only have to include the parameters that you actually use.
    4. Before .Net 4.0 you frequently had to use casts, because most COM methods receive and return variant types. The new dynamic support means that you are no longer required to cast these objects into appropriate types.
    5. Create another a C# Console Application project. In Solution Explorer, add references these framework components.
      Microsoft.Office.Interop.Word
      System.IO
    6. Create a Word document called MyFile.doc and add some text. Then save this to the application’s startup path, which is its bin/Debug folder.
    7. Enter this code in the Main method. By employing C#’s new features we have simplified the code.
      Application wordApp = new Application();
      DirectoryInfo di = new DirectoryInfo(".");
      var doc = wordApp.Documents.Open(di.FullName + "\\MyFile.doc");
      doc.CheckSpelling();
    8. Run the application to test it and then save your work.
    9. View code file.

    Back to 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