C# 7 Features Previewed

Over the last year we've shown you various features that were being considered for C# 7. With the preview of Visual Studio 15, Microsoft has decided to demonstrate the features to make it into the final release of C# 7.

Tuple Value Types

.NET has a tuple type, but in the context of C# there are a lot of problems. Being a reference type, you probably want to avoid using it in performance sensitive code as you have to pay for GC costs. And as they are immutable, while making it safer for sharing across threads, making any changes requires allocating a new object.

C# 7 will address this by offering a tuple as a value type. This will be a mutable type, making it more efficient when performance is essential. And as a value type, it makes a copy on assignment so there is little risk of threading issues.

To create a tuple, you can use this syntax:

var result = (5, 20);

Optionally, you can name the values. This isn't necessary, it just makes the code more readable.

var result = (count: 5, sum: 20);

Multi-value Returns

Returning two values from one function has always been a pain in C-style languages. You have to either wrap the results in some sort of structure or use output parameters. Like many functional languages, C# 7 will do the first option for you:

(int, int) Tally (IEnumerable<int> list)

Here we see the basic problem with using generic tuples: there is no way to know what each field is for. So C# is offering a compiler trick to name the results:

(int Count, int Sum) Tally (IEnumerable<int> list)

We'd like to stress that C# isn't generating a new anonymous type. You are still getting back a tuple, but the compiler is pretending its properties are Count and Sum instead of Item1 and Item2. Thus these lines of code are equivalent:

var result = Tally(list);

Note that we do not yet have a syntax for multi-assignment. Presumably when it happens, it will look something like this:

(count, sum) = Tally(list);

Beyond simple utility functions such as this, multi-value returns will be useful for writing asynchronous code, as async functions aren't allowed to use out parameters.

Pattern Matching: Enhanced Switch Blocks

One of the long standing complaints of VB and functional programmers alike is that C#'s switch statement is extremely limited. VB developers want ranges, while those who used to F# or Haskell want decomposition-style pattern matching. C# 7 intends to offer both.

When pattern matching on types, you can create variables to hold the result of the cast. For example, when using a switch on a System.Object you could write:

case int x:

If the object is an integer, the variable x will be populated. Otherwise it will check the next case block in a top to bottom fashion. If you want to be more specific, you can use range checks:

case int x when x > 0:
case int y:

In this example, if the object is a positive integer the x block will be executed. If the object is zero or a negative integer, the y block will be executed.

If you want to check for null, simply use this syntax:

case null;

Pattern Matching: Decomposition

So far we've just seen an incremental improvement over what is available in VB. The real power of pattern matching comes from decomposition, where you can tear apart an object. Consider this syntax:

if (person is Professor {Subject is var s, FirstName is "Scott"})

This does two things:

  1. It creates a local variable named s with the value of
  2. It performs the equality check
    ((Professor)person).FirstName == "Scott"

Translated into C# 6 code:

var temp = person as Professor;
if (temp != null && temp.FirstName == "Scott")
   var s = temp.Subject

Presumably we'll be able to combine enhanced switch blocks in the final release.

Ref Returns

Passing large structures by reference can be significantly faster than passing them by value, as the latter requires copying the whole structure. Likewise, returning a large structure by reference can be faster.

In languages such as C, you return a structure by reference using a pointer. This brings in the usual problems with pointers such as pointing to a piece of memory after it has been recycled for another purpose.

C# avoids this problem by using a reference, which is essentially a pointer with rules. The most important rule is that you can't return a reference to a local variable. If you tried, that variable would be on a portion of the stack that is no longer valid as soon as the function returns.

In the demonstration, they instead returned a reference to a structure inside an array. Since it is effectively a pointer to an element in the array, the array itself can be modified. For example:

var x = ref FirstElement(myArray)
x = 5; //MyArray[0] now equals 5

The use case for this is highly performance sensitive code. You wouldn't use it in most applications.

Binary Literals

A minor feature is the addition of binary literals. The syntax is simple prefix, for example 5 would be "0b0101". The main use cases for this would be setting up flag based enumerations and creating bitmasks for working with C-style interop.

Local Functions

Local functions are functions that you define inside another function. At first glance, local functions look like a slightly nicer syntax for anonymous functions. But they have some advantages.

  • First, they don't require you to allocate a delegate to hold them. Not only does this reduce memory pressure, it also allows the function to be in-lined by the compiler.
  • Secondly, they don't require you to allocate an object when creating a closure. Instead it just has access to the local variables. Again, this improves performance by reducing GC pressure.

Presumably the second rule means that you can't create a delegate that points to a local function. Still, this offers organizational benefits over creating separate private functions to which you pass the current function's state as explicit parameters.

Partial Class Enhancements

The final feature demonstrated was a new way to handle partial classes. In the past, partial classes were based around the concept of code-generation first. The generated code would include a set of partial methods that the developer could implement as needed to refine behavior.

With the new "replace" syntax, you can go the other way. The developer writes code in a straight forward fashion first and then the code generator comes in and rewrites it. Here is a simple example of what the developer may write,

public string FirstName {get; set;}

Simple, clean, and completely wrong for a XAML style application. So here's what the code generator will produce:

private string m_FirstName;
static readonly PropertyChangedEventArgs s_FirstName_EventArgs 
                   = new PropertyChangedEventArgs("FirstName")

replace public string FirstName {
   get {
      return m_FirstName;
   set {
      if (m_FirstName == value)
      m_FirstName = value;
      PropertyChanged?.Invoke(this, m_FirstName_EventArg);

By using the "replace" keyword, the generated code can literally replace the hand-written code with the missing functionality. In this example, we can even handle the tedious parts that developers often skip such as caching EventArgs objects.

While the canonical example is property change notifications, this technique could be used for many "Aspect Oriented Programming" scenarios such as injecting logging, security checks, parameter validation, and other tedious boilerplate code.

New Features in Visual Studio 2015 RC


Visual Studio 2015 RC has major changes including an integrated suite of developer productivity tools, cloud services and extensions that enable you and your team to create great apps and games for the web, for Windows Store, for the desktop, for Android and for iOS. This article highlights some of the most important features in the Visual Studio 2015 RC IDE.

The following are the new features in Visual Studio 2015 RC.

  1. Sign In across multiple accounts

    You can work with multiple user accounts in Visual Studio by adding them as you go or through the new Account Manager. Then, you can switch among those accounts on the fly when connecting to services or accessing online resources. Visual Studio remembers the accounts you add so you can use them from any instance of Visual Studio or Blend.


    Figure 1: You can add multiple accounts in Visual Studio by clicking on Add an account link

  2. Choose your target platform(s)

    Visual Studio 2015 supports cross-platform mobile device development. You can write apps and games that target iOS, Android and Windows and share a common code base, all from within the Visual Studio IDE. You'll see all these new project types in the File, New Project dialog.

    And also support for classic desktop applications are better than ever, with many improvements to languages, libraries and tools. The following are the various platforms.

    • Cross-platform mobile apps in C# with Xamarin for Visual Studio
    • Cross-platform mobile apps in HTML/CSS/JavaScript with Apache Cordova
    • Cross-platform mobile games in C# with Unity
    • Classic desktop and Windows Store
    • Cross-platform mobile games in C# with Unity
    • Cross-platform apps and libraries for native C++
    • Web

    ASP.NET 5 is a major update to MVC, Web API and SignalR and runs on Windows, Mac and Linux. ASP.NET 5 has been designed from the ground up to provide you with a lean and composable .NET stack for building modern cloud-based apps. The Visual Studio 2015 RC tooling is more closely integrated with popular web development tools such as Bower and Grunt.
  3. Live code analysis (Light Bulbs)

    In Visual Studio 2015 RC, light bulbs display in the left margin (when using the keyboard) or a tool tip (when hovering over an error with the mouse). The light bulbs indicate in real time that the compiler (possibly using a custom rule set) has detected an issue in your code and also has a suggestion for how to fix the issue. When you see a light bulb, click on it for actionable suggestions.


    Figure 2: Live code analysis - image reference from MSDN site

  4. Design your UI

    The Blend experience for designing XAML user interfaces has been significantly enhanced. Blend has been completely redesigned to provide a more intuitive UI, more powerful XAML editing capabilities and better integration with Visual Studio.
  5. Diagnose Issue

    • Advance Breakpoints

      Breakpoints in the debugger are significantly more configurable and the UI for interacting with breakpoints is consolidated into a peek window so that you never need to leave the code editor.


      Figure 3: Breakpoint with expression condition -Image reference from MSDN site

    • Performance Tips

      Performance tips display the execution time of methods during debugging, enabling you to quickly spot bottlenecks without having to invoke the profiler.


      Figure 4: Elapsed time (Image from MSDN site)

    • Error List

      The error list now supports filtering on any column. It is also scalable enough to show a live view of errors, warnings and code analysis across your entire C# or Visual Basic solution as you type, even when a code change produces thousands of warnings. The new Error List is backward-compatible with existing usage.
    • GPU Usage Tool

      The GPU Usage Tool helps you collect and analyze GPU usage data in DirectX apps and games and troubleshoot whether performance bottlenecks are originating in the CPU or GPU.
  6. Connect To Service

    The Add Connected Service wizard also integrates with the new Account Manager to make it easy to work with multiple user accounts and subscriptions. In Visual Studio 2015 RC, support for the following services are provided out of the box (assuming that you have an account):

    • Azure Mobile Services
    • Azure Storage
    • Office 365 (mail, contacts, calendars, files, users and groups)
    • Salesforce


    Figure 5: Add Connected Service (Image from MSDN site)

  7. Synchronized Settings (Roaming Settings)

    Visual Studio 2015 improves on this experience by synchronizing more of your settings and synchronizing settings across the Visual Studio family of applications, like Professional, Enterprise, Express SKUs and Blend. Settings includes settings for some of the most commonly configured settings such as Text Editor, Key bindings, Theme and Fonts and Colors, Startup and Environment Aliases
  8. High Resolution Images and Touch Support

    The Visual Studio IDE now has true high-resolution images on denser displays (in areas like menus, context menus, tool window command bars and in some projects in Solution Explorer). And on a touch-screen in the Visual Studio code editor window, you can now use gestures such as touch and hold, pinch, tap and so on to zoom, scroll, select text and invoke context menus.
  9. Title Case Menu

    Visual Studio menus are once again title-case by default. However if you happen to like the ALL CAPS style, you can set it on start up or in the Tools > Options > General property page as in the following:


    Figure 6: Title Case Menu- Image reference from MSDN site

  10. Custom Layouts

    You can create store and roam custom window layouts. For example, you can define one preferred layout for use on your desktop machine and a different layout for use on a laptop or small screen device. Or you may prefer one layout for a UI project and another for a database project. Key bindings enable you to rapidly switch among layouts. These layouts are available on any instance of Visual Studio when you are signed in.


    Figure 7:
    Custom Layout (Image from MSDN site)

  11. Notification Hub

    The UI for the notification hub has been streamlined to make it easier to scan quickly. Additional kinds of notifications have been added, including performance issues, rendering issues and crashes and you can now tell Visual Studio to stop showing a notification.


    Figure 8: Notification Hub (image from MSDN site)

  12. Code Lens: Find what happened to your code (Enterprise and Professional editions only)

    You can review changes and other history for work items, bugs, code reviews and so on for code that's stored in Visual Studio Online (VSO) or in Team Foundation Server (TFS).

    In Visual Studio Enterprise and Visual Studio Professional, you can now:

    • Get the history for an entire code file in the Visual Studio editor.


      Figure 9:
      Code Lens (image from MSDN site)

    • See a graph that shows the people that have changed your code. This can help you find patterns in your team's changes and assess their impact.

      Figure 10: Code Lens (image from MSDN site)

    • Easily see when your code was last changed.
    • Find changes in other branches that affect your code.

Main Reference: MSDN library https://msdn.microsoft.com for image references also.

Microsoft explains what you’ll lose by upgrading to Windows 10

Microsoft announced today that it will be launching Windows 10 on July 29th, encouraging Windows 7 and 8.1 users to reserve their free upgrade with a notification in their task bar. However, while the company has been busy highlighting all the shiny new features in the upcoming OS, it's been a bit quieter when it comes to spelling out the limitations — including making updates automatic for Windows 10 Home users.

Firstly there are the software losses. Most of these will only affect a small number of users, but upgrading will mean saying goodbye to Windows Media Center, the card game Hearts, and Windows 7's desktop gadgets. Anyone in the habit of using floppy disks on Windows will also have to install new drivers, and Microsoft warns that watching DVDs will also require "separate playback software." Microsoft manager Gabriel Aul has said on Twitter that a DVD option for Windows 10 is coming later this year," but early upgraders can always download VLC instead.

In addition to the software losses, there are also a number of limitations for some of Windows 10's most exciting features. Cortana will only be available in the US, UK, China, France, Italy, Germany, and Spain at launch, while Windows Hello (which offers support for various biometric passwords) will need an infrared camera for facial recognition, or a supported fingerprint reader. The Xbox Music and Xbox Video streaming apps will also be constrained by the usual, complex web of region-based licenses.

More annoyingly, perhaps, Microsoft has also changed how updates will work with Windows 10. Although the Pro and Enterprise editions will both be able to defer updates, Windows 10 Home users will not have the option. Updates will instead be downloaded and installed automatically as soon as they're available. System requirements for the new OS have also been detailed, with PCs and tablets needing to pass a fairly low bar: a 1GHz processor, 1GB of RAM, 16GB of storage, and a display resolution of at least 1,024 x 600 are required. These specs are a bit higher for the 64-bit version of Windows 10 but for these details and more, you can check out Microsoft's full specs page.