What’s new in C# 6.0

I just installed Visual Studio 2015 Preview on a Windows 10 tech. preview, the first thing I wanted to try out was C# 6.0.

Source code

VisualStudio2015 in Windows10

VisualStudio 2015 in Windows10

The are a lot of videos and posts on internet about the new features of C# 6.0. The goal of this post is to test them by myself and share my impressions. I will use this post in the future as a personal reference for C# 6.0 new features.

C# 6.0 new feautures

This is the list of new features I have collected so far:

  • Getter only auto properties
  • Auto-Initialization of properties
  • Calculated properties with body expressions
  • Null conditional operators ?.
  • Operator nameof()
  • Strings projections
  • Exceptions filters
  • Await in catch and finally
  • Index initializers

I wrote a small sample class that I will use as an example to test the new features.

This is the C# 5 sample class:

using System;

namespace ConsoleApplication1
{
    public class Person
    {
        public Person(string name, int age)
        {
            if (name == null)
            {
                throw new NullReferenceException("name");
            }

            Name = name;
            Age = age;
            Id = GetNewId();
        }

        public string Name { get; set; }
        public int Id { get; private set; }
        public int Age { get; set; }

        public event EventHandler Call;

        protected virtual void OnCall()
        {
            EventHandler handler = Call;
            if (handler != null) handler(this, EventArgs.Empty);
        }

        public int GetYearOfBirth()
        {
            return DateTime.Now.Year - Age;
        }

        public JObject ToJSon()
        {
            var personAsJson = new JObject();

            personAsJson["id"] = this.Id;
            personAsJson["name"] = this.Name;
            personAsJson["age"] = this.Age;

            return personAsJson;
        }

        #region Get new person id

        private static int lastId;

        private static int GetNewId()
        {
            lastId++;
            Logger.WriteInfo(string.Format("New Id = {0}", lastId));
            return lastId;
        }

        #endregion
    }
}

Applying C# 6.0 new features to a C# 5.0 class:

Now lets go throw the list of new features and apply them to our sample class:

Getter only auto properties

We can remove “private set” from read-only properties, properties with only a “setter” can be initialized only from the constructor or with auto-initialization.

public int Id { get; }     

Auto-Initialization of properties

Using auto initialization we can auto initialize the Id property calling a method. It is also possible to set a default value to editable properties:

public int Id { get; } = GetNewId();    
public int Age { get; set; } = 18;    

Calculated properties with body expressions

It is common to have a lot of single line calculated properties or methods on our code. In lambda expressions it was already possible to write only the value to return. Now this is also possible in normal methods:

Our “GetYearOfBirth” method can be re-write like this:

     
public int GetYearOfBirth => DateTime.Now.Year - Age;

Note that if the method has not parameters we can also avoid the parentheses.

Null conditional operators ?.

Continue reading

WPF – State machine and ICommand

The goal of this post is to test the usage of MVVM Delegate commands together with a state machine.  You can read more about the state machine pattern here, and about commands here.

WPF allows to bind a command to some controls, the ICommand interface has two methods:  one that executes an action and one that returns  a Boolean indicating if the command can be executed or not.

E.g. Command bound to a button: When the button is clicked the action defined within the command is executed, when the command cannot be executed the button is disabled.

This is the ICommand interface.

public interface ICommand {
	event EventHandler CanExecuteChanged;
	bool CanExecute(object parameter);
	void Execute(object parameter);
}

I will use the Microsoft PRISM 5 Delegate ICommand implementation and the stateless state machine.

ICommand + State Machine Trigger

On a state machine there are states and triggers, within one state some triggers are forbidden and other are allowed, when a trigger is fired the state machine could change its state.

Our commands shall be associated to a trigger, the behaviour should be:

  • CanExecute: Shall return true only if the associated trigger can be fired on the current state.
  • Execute: Shall fire the associated trigger, the machine could change its state.

The coffee machine

The application that we will write will be a very simple coffee machine with only one type of coffee:

States

  1. Idle: Machine waiting to be used.
  2. With money: The user entered some money but is not enough to get a coffee.
  3. Can get coffee: The user entered enough money to get a coffee.
  4. Preparing coffee: The coffee is being prepared.
  5. Coffee ready: The user can take the coffee.
  6. Refunding money: The machine is returning the money to the user.

Triggers

  1. Insert money: Fired when the user insert money.
  2. Refund money: Fired when the user press the refund money button and after the user takes the coffee.
  3. Enough money: Automatically fired when the user inserted enough money.
  4. Prepare coffee: Fired when the user select a coffee, (our machine is that simple that has only one…)
  5. Coffee prepared: Automatically fired when the coffee is prepared.
  6. Take coffee: Fired when the user takes the coffee.
  7. Money refunded: Automatically fired when the machine refunded the money.

The diagram

image

Implementation

States

    public enum CoffeeMachineState
    {
        Idle,
        WithMoney,
        CanSelectCoffee,
        PreparingCoffee,
        CoffeeReady,
        RefundMoney
    }

Triggers

    public enum CoffeeMachineTrigger
    {
        InsertMoney,
        RefundMoney,
        PrepareCoffee,
        TakeCoffe,

        // Automatic triggers
        EnoughMoney,
        CoffeePrepared,
        MoneyRefunded
    }

Configuration

        /// <summary>
        /// Configures the machine.
        /// </summary>
        private void ConfigureMachine()
        {
            // Idle
            this.Configure(CoffeeMachineState.Idle)
                .Permit(CoffeeMachineTrigger.InsertMoney, CoffeeMachineState.WithMoney);

            // Refund money
            this.Configure(CoffeeMachineState.RefundMoney)
                .OnEntry(RefundMoney)
                .Permit(CoffeeMachineTrigger.MoneyRefunded, CoffeeMachineState.Idle);


            // WithMoney
            this.Configure(CoffeeMachineState.WithMoney)
                .PermitReentry(CoffeeMachineTrigger.InsertMoney)
                .Permit(CoffeeMachineTrigger.RefundMoney, CoffeeMachineState.RefundMoney)
                .Permit(CoffeeMachineTrigger.EnoughMoney, CoffeeMachineState.CanSelectCoffee);

            // CanSelectCoffee
            this.Configure(CoffeeMachineState.CanSelectCoffee)
                .PermitReentry(CoffeeMachineTrigger.InsertMoney)
                .Permit(CoffeeMachineTrigger.RefundMoney, CoffeeMachineState.RefundMoney)
                .Permit(CoffeeMachineTrigger.PrepareCoffee, CoffeeMachineState.PreparingCoffee);

            // PreparingCoffee
            this.Configure(CoffeeMachineState.PreparingCoffee)
                .OnEntry(PrepareCoffee)
                .Permit(CoffeeMachineTrigger.CoffeePrepared, CoffeeMachineState.CoffeeReady);

            // CoffeeReady
            this.Configure(CoffeeMachineState.CoffeeReady)
                .Permit(CoffeeMachineTrigger.TakeCoffe, CoffeeMachineState.RefundMoney);

            this.OnTransitioned(NotifyStateChanged);
        }

StateMachine command factory

Continue reading