dotnet

3 Awesome New C# Features

A new version of C# is on the way. Here are 3 new features to make your life easier.

New additions in C# 6 are focused on making developers more productive - getting more done with less code. Let’s start with a nice new operator.

Null Propogation Operator

Most C# devs will be familiar with this sort of code:


if (businessThing != null) && (businessThing.OtherThing != null) {
  if (businessThing.OtherThing.NestedThing != null) {
    businessThing.OtherThing.NestedThing.DoThings();
  }
}

A common repetitive task is to check that an object is not null, and if it is not null, do somthing with one of the objects properties.

Now we have this shiny new operator:

?.

This is the null propation operator. It does a null check of a property, and if that null check passes, it then accesses the property. If the null check doesn’t pass, it jumps out of the statement and continues program execution without throwing an exception.

Our ugly block of code above, becomes this:

businessThing?.OtherThing?.NestedThing.DoThings();

It really improves readability, as well as making your code more consise.

Nameof Expression

This tells us the name of a variable. Here’s a use case:


public void PrintFavourites(string animal, string food) {
  // using nameof
  if (animal == null)
    throw new ArgumentNullException(nameof(animal));

  // using magic strings, bad
  if (food == null)
    throw new ArgumentNullException("food");

  // do stuff
}  

Cool huh?

Auto Property Initialisers

Auto properties are great, but up until now we can’t auto initialise them, which is less than great for a read only property. Currently we need to:

  1. Create backing field
  2. Initialise the backing field in our constructor
  3. Explicitly create the property, referencing the backing field

C#6 brings us auto property initialisers, allowing declaration and initialisation in a single line:

public string Bob { get; } = "Dave";

Bam. Done.

How long do I have to wait?!?!

C#6 will be shipping with VS2015, which recently had the developer preview released. The release date isn’t finalised yet.

You can get more details on C#6 here, and more detail on VS2015 here.

/eof

Auto mocking with AutoMoq

AutoMoq is a nice little package I came across today. The AutoMoq home page describes it as follows:

AutoMoq is an "auto-mocking" container that creates objects for you. Just tell it what class to create and it will create it.

Why is this useful? Consider the following scenario. We have a BananaCakeFactory class, that relies on a Banana Repository.

Here is the constructor:


public BananaCakeFactory(IBananaRepo bananaRepo);

If we want to run Unit Tests on methods in BananaCakeFactory, we will have to write all the mocking code to mock IBananaRepo. That’s fine.

Time goes on, our app grows more complex. Now our BananaCakeFactory needs to Sugar Repo as well…


public BananaCakeFactory(IBananaRepo bananaRepo, ISugarRepo sugarRepo);

We add mocks for our Sugar Repo, and update all our constructor calls for BananaCakeFactory. When we have a large solution, time spent adding new mocks and updating constructors really adds up. AutoMoq can take the pain away.

Here is an example of how we use AutoMoq to create a mocked class, ready for testing:


// init
mocker = new AutoMoqer();

// mock a Banana Cake Factory
var cakeFac = mocker.Create<BananaCakeFactory>();

// inject our IRepo
mocker.GetMock<IBananaRepo>();

// do work
var result = cakeFac.Bake();

Now if we want to add our Sugar Repo, all that’s needed is the following additional line:


mocker.GetMock<ISugarRepo>();

Happy Coding!

Reference URLs

  • AutoMoq Homepage
  • AutoMoq Nuget Package
  • /eof

    Nested Dependencies in MVC4

    Given how complex the average MVC4 application can become, it is likely that you are going to come across the situation where you build up a dependency chain. It may look like this: Controller -> Provider/Manager -> Dependency

     A common scenario may be that your controller needs a Lookup Manager, and that manager needs a cached query passed in.

    In this scenario, the Unity.Mvc4 nuGet package comes into play.

    Here is our home controller:

    
    // Home controller
    public class HomeController : AsyncController
    {
        private ILookupManager<StatusLookup> statusLookup;
    
        // constructor with lookup dependency
        public HomeController(ILookupManager<StatusLookup> statusLookup)
        {
            this.statusLookup = statusLookup;
        }
    }
    

    Notice that the constructor requires the StatusLookup.

    Here is the Status Manager implementation. Observe that it is a generic class, expecting a StatusLookup object. The constructor requires a query passed in (of type IQuery).

    
    //LookupManager.cs
    public class LookupManager<T> : ILookupManager<T> where T : ILookupField
    {
        private IQuery<T> _query;
    
        // lookup manager has a Query dependency
        public LookupManager(IQuery<T> query)
        {
            _query = query;
        }
    
        public List<T> Lookup()
        {
            // return lookup query result
            return _query.Get();
        }
    }
    

    This is where life gets easy. After installing the Unity.Mvc4 nuGet package, our MVC project gains a “boostrapper” class. This provides us with a simple mechanism to get any dependency into any class in our MVC app. It works by utilising the Unity Dependency Injection container.

    
    // Boostrapper.cs
    // Added by the Unity.Mvc4 NuGet package
    private static IUnityContainer BuildUnityContainer()
    {
        var container = new UnityContainer();
    
        // initialise Status lookup
        container.RegisterType<IQuery<StatusLookup>, QueryStatusLookup>();
    
        // make Status lookup available to mvc4 controllers
        container.RegisterType<ILookupManager<StatusLookup>, LookupManager<StatusLookup>>();
    
        RegisterTypes(container);
        return container;
    }
    

    If we have a look at the BuildUnityContainer() method, there are two calls to container.RegisterType(). The first is to provide the IQuery dependency to StatusLookup. The second is to provide the StatusLookup dependency to our HomeController.

    To keep it all manageable, make sure your dependencies are passed using an interface (ILookupManager, and IQuery in my case).

    /eof