Given, When, Then

Given-When-Then is a style of representing tests specifying a system's behavior. It's an approach developed by Dan North and Chris Matts as part of Behavior-Driven Development (BDD). It appears as a structuring approach for many testing frameworks such as Cucumber. You can also look at it as a reformulation of the Four-Phase Test pattern.

The essential idea is to break down writing a scenario (or test) into three sections:

  • The given part describes the state of the world before you begin the behavior you're specifying in this scenario. You can think of it as the pre-conditions to the test.
  • The when section is that behavior that you're specifying.
  • Finally the then section describes the changes you expect due to the specified behavior.

Since we're talking about using examples as specifications, it makes sense to show this with an example

Feature: User trades stocks
  Scenario: User requests a sell before close of trading
    Given I have 100 shares of MSFT stock
       And I have 150 shares of APPL stock
       And the time is before close of trading

    When I ask to sell 20 shares of MSFT stock
     
     Then I should have 80 shares of MSFT stock
      And I should have 150 shares of APPL stock
      And a sell order for 20 shares of MSFT stock should have been executed
  

The above example uses Cucumber, which a popular way of writing BusinessFacingTests but you can use the Given-When-Then style with any kind of tests. Some people like to put Given-When-Then as comments to mark informal blocks inside unit tests. I've also seen this convention to structure informal prose.

It's usual with this approach to see "ands" used to combine multiple expressions within each clause.

I've characterized the given as a description of the pre-condition state because that's the way I prefer to think of it. A testing framework, however, interprets the givens as a set of commands to bring the system-under-test into the correct state before executing the when command. Testing frameworks provide various query methods for the then commands - these should be free of side-effects.

Although Given-When-Then style is symptomatic to BDD, the basic idea is pretty common when writing tests or specification by example. Meszaros describes the pattern as Four-Phase Test. His four phases are Setup (Given), Exercise (When), Verify (Then) and Teardown. Bill Wake came up with the formulation as Arrange, Act, Assert.

7 Popular Unit Test Naming Conventions

Following are 7 popular unit tests naming conventions that are found to be used by majority of developers and compiled from above pages:

  1. MethodName_StateUnderTest_ExpectedBehavior: There are arguments against this strategy that if method names change as part of code refactoring than test name like this should also change or it becomes difficult to comprehend at a later stage. Following are some of the example:
    • isAdult_AgeLessThan18_False
    • withdrawMoney_InvalidAccount_ExceptionThrown
    • admitStudent_MissingMandatoryFields_FailToAdmit
  2. MethodName_ExpectedBehavior_StateUnderTest: Slightly tweeked from above, but a section of developers also recommend using this naming technique. This technique also has disadvantage that if method names get changed, it becomes difficult to comprehend at a later stage. Following is how tests in first example would read like if named using this technique:
    • isAdult_False_AgeLessThan18
    • withdrawMoney_ThrowsException_IfAccountIsInvalid
    • admitStudent_FailToAdmit_IfMandatoryFieldsAreMissing
  3. test[Feature being tested]: This one makes it easy to read the test as the feature to be tested is written as part of test name. Although, there are arguments that the “test” prefix is redundant. However, some sections of developer love to use this technique. Following is how the above tests would read like if named using this technique:
    • testIsNotAnAdultIfAgeLessThan18
    • testFailToWithdrawMoneyIfAccountIsInvalid
    • testStudentIsNotAdmittedIfMandatoryFieldsAreMissing
  4. Feature to be tested: Many suggests that it is better to simply write the feature to be tested because one is anyway using annotations to identify method as test methods. It is also recommended for the reason that it makes unit tests as alternate form of documentation and avoid code smells. Following is how tests in first example would read like if named using this technique:
    • IsNotAnAdultIfAgeLessThan18
    • FailToWithdrawMoneyIfAccountIsInvalid
    • StudentIsNotAdmittedIfMandatoryFieldsAreMissing
  5. Should_ExpectedBehavior_When_StateUnderTest: This technique is also used by many as it makes it easy to read the tests. Following is how tests in first example would read like if named using this technique:
    • Should_ThrowException_When_AgeLessThan18
    • Should_FailToWithdrawMoney_ForInvalidAccount
    • Should_FailToAdmit_IfMandatoryFieldsAreMissing
  6. When_StateUnderTest_Expect_ExpectedBehavior: Following is how tests in first example would read like if named using this technique:
    • When_AgeLessThan18_Expect_isAdultAsFalse
    • When_InvalidAccount_Expect_WithdrawMoneyToFail
    • When_MandatoryFieldsAreMissing_Expect_StudentAdmissionToFail
  7. Given_Preconditions_When_StateUnderTest_Then_ExpectedBehavior: This approach is based on naming convention developed as part of Behavior-Driven Development (BDD). The idea is to break down the tests into three part such that one could come up with preconditions, state under test and expected behavior to be written in above format. Following is how tests in first example would read like if named using this technique:
    • Given_UserIsAuthenticated_When_InvalidAccountNumberIsUsedToWithdrawMoney_Then_TransactionsWillFail

Google AI can make calls for you

During the on-stage demonstration, Google played calls to a number of businesses including a hair salon and a Chinese restaurant. At no point did either of the people on the other end of the line appear to suspect that the entity they were interacting with was a bot. And how could they when the Assistant would even throw in random "ums", "ahhs" and other verbal fillers people use when they're in the middle of a thought? According to the company, it's already generated hundreds of similar interactions over the course of the technology's development.

MongoDb example

Simple example for MongoDB. Save and retrieve data from Azure Cosmos DB.

Create an Azure Cosmos Db as MongoDb

For creating a new MongoDb on Azure, search from the list of resources, Azure Cosmos Db. Then Add a new database and you see the following screen.

Add new CosmosDB

Overview

When you created a new MongoDb, you see an Overview where there are general information about how many queries the database did (split on insert, update, cancel, query, count, others).

Azure Overview

Under Connection String you have the connection to use in your application. In this project you insert in Program.cs the connection string in the variable called connectionString.

DataExplorer

You can explorer all data in your Mongo database. Click on Data Explorer and you can see everything. Also, you can execute same queries.

Azure CosmosDb Data Explorer

You find an example application on my GitHub.

Never give up!

amazon-bezof-never-give-up

Surface phone: is it the real time?

Surface-phone

Surface Phone Rumors: Microsoft to Finally Unveil Mythical Device at the MWC 2018.

While some people are resigned to the fact that the long-rumored Surface Phone is nothing more than a figment of the imagination, new reports claim that the long-rumored mythical Microsoft device may finally be unveiled at next month's MWC (Mobile World Congress).

Rumors about the Surface Phone have been in existence for two years now, but no one outside Microsoft cannot really confirm if the device is in the pipeline. However, according to recent reports, the wait may be soon over as it is alleged that the Redmond-based company will reveal the Surface Phone at the annual MWC happening at Barcelona next month.

Surface-phone-2

Surface-phone-1

First AngularJs example

If you are looking around for a new job as .NET developer, all companies are asking you AngularJs. Then I’m starting to learn it and I share with you the secret of this framework.

I’m assuming you are a .NET developer like me and you want to learn AngularJs and then I won’t explain you the basis of HTML.

Open Visual Studio and create a new solution with ASP.NET Empty web Site.

AnguarJS1-CreateEmptySolution-VisualStudio2017

Now you have your project.

AnguarJS1-EmptySolution-VisualStudio2017

Add from NuGet AngularJS.Core.

AnguarJS1-AddAngularJs-from-NuGet-VisualStudio2017

Done. We start now with a little complicate example. Two examples.

StartHere.html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="Scripts/angular.min.js"></script>
</head>
<body ng-controller="ExampleController">
    <h1>Game setup</h1>
    <div ng-repeat="player in players" 
        ng-init="playerIndex = $index">
        <ng-include src="'player.html'"></ng-include>
    </div>
    <script>
        (function () {
            "use strict";
            var myAppModule = angular.module('myApp', []);

            myAppModule.factory('playerService', function () {
                var playerCount = 0;
                var createDefaultPlayer = function () {
                    playerCount += 1;
                    var player = {
                        name: "",
                        prevName: ""
                    };

                    player.onNameFocused = function () {
                        player.prevName = player.name;
                    };
                    return player;
                }

                return {
                    createPlayer: function (name) {
                        var player = createDefaultPlayer();
                        player.name = name;
                        return player;
                    },
                    getPlayerCount: function () {
                        return playerCount;
                    }
                };
            });

            myAppModule.controller('ExampleController', ['$scope', 'playerService',

                function ($scope, playerService) {

                    $scope.players = [playerService.createPlayer('Player1'),
                        playerService.createPlayer('Player2'),
                        playerService.createPlayer('Player3')];

                }

            ]);
        }());
    </script>
</body>
</html>

player.html

<h2>Player {{$playerIndex + 1}}</h2>
<label>Name:</label>
<input type="text" placeholder="Enter Player {{$playerIndex + 1}}" 
    ng-model="player.name" ng-focus="player.onNameFocused()" />
<h3 ng-show="player.name">
    Player {{$playerIndex + 1}} name is {{player.name}}
</h3>
<h3 ng-show="player.prevName">
    Prev Player {{$playerplayerIndex + 1}} name was 
    {{player.prevName}}
</h3>

Explanation

JavaScript frameworks such as Backbone.js, knockout.js, AngularJs and others addressed the problems of scalability, reusability, and testability by embracing a design pattern traditionally used by server-side frameworks.

This pattern is called Model-View-Controller (MVC), and it is an established pattern that was originally introduced in the 1970s. You should already be familiar with it from the ASP.NET MVC fundamentals, but I will revisit it here for reference.

Technically, AngularJS uses a variant of the MVC, which is closer to the Model-View-ViewModel (MVVM) pattern, but the definition of MVC from the next section still applies to it. One of the core members of the AngularJS team declared the main design pattern behind AngularJS as being "Model-View-Whatever works for you" (MVW or MV*) in this post at http://plus.google.com/+AngularJS/posts/aZNVhj355G2.

The design pattern is specific for applications with user interfaces and introduces a separation between the following aspects:

  • Model: This is the application data and the business logic associated with it

  • View: This is the output of the application data in any form that can be consumed or manipulated by a user

  • Controller: This is the logic to get data from the View to the Model and back, and to manage any interaction with the View or the Model

The first highlighted attribute is ng-app, which has a value this time around. The myApp value represents the unique identifier of the current AngularJS application. The next highlighted code initializes a new AngularJS component called module, which will be used via the myApp identifier to bootstrap the AngularJS application.

A module is a container-like object with a unique identifier that groups together the AngularJS components used to build an application: controllers, directives, and others, such as providers, factories, services, values, constants, animations, and filters. The module has methods that are specific to the AngularJS application components I mentioned.

The module controller function takes the controller name and controller constructor function as arguments.

The first highlighted snippet is the service definition that looks similar to a controller definition, with the exception that it returns an object that represents the service factory. This object is used to create the service instance that will be injected in all of the AngularJS components that have this service declared as a dependency.

In the new service, we transformed the previous controller code into a function called createDefaultPlayer(), which will create a new object that represents a player. The service instance has a method to create a new player with a predefined name called createPlayer(name). The service factory function will keep track of how many player objects were created using the playerCount variable. The variable will be returned by the service instance function, getPlayerCount(). On a side note, you can see the revealing module pattern in action here. Although the script section is now bigger, we obtained new features such as code reusability and flexibility to provide more complex functionality than before.

There are other methods available on the module interface to declare an AngularJS service, such as service, value, and constant. The service method will use a constructor function to create the service instance, while the value method will use an already created service instance that will be passed unchanged to the AngularJS injector. The constant method is similar with the value method, with the difference that it will be available during the configuration phase of the application module. The factory method is one of the most flexible methods, and it will be the most frequently used method in the rest of the examples from this book. It allows additional configuration to the returned service instance, and you can even keep track of data outside of the service instance, such as with the playerCount variable from the previous example.

We have used a lot of directives in the examples presented so far, and most of them used the ng- prefix. When you take a look at the directives' documentation pages at http://code.angularjs.org/1.2.15/docs/api, you will notice that the directive names appear slightly different—ng-app is ngApp and ng-controller is ngController. AngularJS removes any data- or x- prefixes from the HTML markup and converts the -, _, and : characters to a camel case directive name. From now on, we will refer to different directives using the names from the AngularJS documentation.

We will explore some important built-in directives and see how to build custom directives. Looking back at the previous example, the HTML markup seems to have been duplicated for the two players. There is a built-in directive called ngRepeat that allows us to remove the duplicated markup as highlighted in the next example.

The ngRepeat directive works with a collection of objects and repeats an HTML markup section for each item in the collection. We created an array of player items in the controller that is used in the ngRepeat directive. The first highlighted code section shows the expression used to iterate through the collection, and the div element that has the directive is repeated for each item in the collection. The player variable defined in the ngRepeat expression is only available inside of the directive. The ngRepeat directive has its own scope that contains other directive-specific variables such as $index, which has been used in the next highlighted code snippet. This variable of the type number keeps track of the current collection item index, and there are other directive-specific Boolean variables available: $first, $middle, $last, $odd, and $even.

The example works for HTML markup that repeats a single element. When the HTML markup that needs repeated elements has separate start and end elements, you need to use two different directive attributes. The first is ng-repeat-start, which is a renamed ng-repeat directive that needs to be used on the start HTML element. The second is ng-repeat-end, which does not have an expression value and is used on the HTML element that ends the markup that needs repeated elements. The previous example of the body element content can now be written using the h2 element as the start of the repeated markup and the h3 element as the end, as shown in the following code:

  <h1>Game setup</h1>
  <div>
    <h2 ng-repeat-start="player in players">
        Player {{$index + 1}}
    </h2>
    <label>Name:
    <input type="text" placeholder="Please enter player {{$index + 1}} name" 
        ng-model="player.name" ng-focus="player.onNameFocused()">
    <h3 ng-show="player.name">Player {{$index + 1}} name is {{player.name}}.</h3>
    <h3 ng-repeat-end ng-show="player.previousName">
        Previous Player {{$index + 1}} name was 
        {{player.previousName}}.
    </h3>
  </div>

The ngRepeat directive example is very useful when we need to manipulate the HTML for a specific application view. However, I can easily imagine scenarios where the HTML for a player has to be reused between different views. If there is a single player game, we want to see only one player editing form rather than two. AngularJS offers a simple but powerful solution through the ngInclude directive. This directive allows the referencing of a separate file that will be loaded and rendered in the current HTML view by AngularJS.

To introduce this directive, I had to change the HTML for the ngRepeat example and add a new file that contains the player HTML markup.

The first highlighted attribute is a new directive, ngInit, that evaluates an arbitrary expression. Although this directive can be used anywhere, it is best practice to only use it in the context of the ngRepeat directive. We use it to create a new scope property that is an alias of the $index variable from the ngRepeat directive. The reason behind this alias is to allow the reuse of the player markup in contexts where there is no enclosing ngRepeat directive.

The next highlighted element is the ngInclude directive, which fetches the referenced player.html file, renders it, and creates a new scope for it. The scope inherits the current ngRepeat iteration scope and its player and playerIndex properties. The last highlighted expression shows how the property created by ngInit is used in player markup.

Add a macOS project to your existing solution

With the new version of Xamarin, we can create apps for macOS. But how can I add a macOS project to my solution? I explain step by step what we have to do.

Add new project

The first step is to add a new project for macOS in your solution. Right-click on your solution and select Add New project... Step 1 - Add new project

Now select from the list App under Mac and then Cocoa App.Step 2 - Select project type

Then name your project, usually, we call this project with yourprojectname.macOS. Step 3 - Name your project

How you see in the preview, the name in the dock it is not very nice. Then we can change it: check Use a Different App Name in Dock and then type the app name.Step 4 - Change name for dock

At the end select the folder where you want to save your project, usually, in the root of your folder in the filesystem.Step 5 - Select project folder

Add packages

In your new project add under Packages Xamarin.Forms and all your other packages you are using in the other project.

Now we have to add the main project. Under References, select the main project and the other dependencies. Edit references

Update the code

Now the complicated part is starting. In your Info.plist file, we have to remove NSMainStoryboardFile.Edit Info.plist

Now in your macOS project, we have to delete Main.storyboard because we don't need it anymore. Right-click on Main.storyboard and then select Remove.

Main.storyboard in your projectMain.storyboard delete

Open your Main.cs and change the Main function with the following code:

static class MainClass
{
    static void Main(string[] args)
    {
        NSApplication.Init();
        NSApplication.SharedApplication.Delegate = new AppDelegate();
        NSApplication.Main(args);
    }
}

Open AppDelegate.cs and add at the top the following packages:

using Xamarin.Forms;
using Xamarin.Forms.Platform.MacOS;

You see now AppDelegate derives from NSApplicationDelegate. Change NSApplicationDelegate with FormsApplicationDelegate. Now you see that AppDelegate is underlined with a red line. We take care of that shortly.

Now add in the AppDelegate body 

NSWindow window;

We override MainWindow function (Visual Studio helps to create this function with the correct signature). As return, we use window.

public override NSWindow MainWindow
{
    get
    {
        return window;
    }
}

Now we have to display a window. For that we have to change AppDelegate(). For creating a window, we have to define its style and dimension.

public AppDelegate()
{
    var style = NSWindowStyle.Closable | NSWindowStyle.Resizable | 
                NSWindowStyle.Titled;
    var rect = new CoreGraphics.CGRect(100, 100, 1024, 768);

    window = new NSWindow(rect, style, NSBackingStore.Buffered, false);
    window.Title = "WordBank Easy";
    window.TitleVisibility = NSWindowTitleVisibility.Hidden;
}

The last thing to do, it is the inizialization of Xamarin.Forms and your app. We change now DidFinishLaunching

public override void DidFinishLaunching(NSNotification notification)
{
    Forms.Init();
    LoadApplication(new App());

    base.DidFinishLaunching(notification);
}

Pretty easy, isn't it? Here my complete code of AppDelegate.cs

using AppKit;
using Foundation;
using Xamarin.Forms;
using Xamarin.Forms.Platform.MacOS;

namespace WordBankEasy.macOS
{
    [Register("AppDelegate")]
    public class AppDelegate : FormsApplicationDelegate
    {
        NSWindow window;

        public override NSWindow MainWindow
        {
            get
            {
                return window;
            }
        }

        public AppDelegate()
        {
            var style = NSWindowStyle.Closable | 
                        NSWindowStyle.Resizable | 
                        NSWindowStyle.Titled;
            var rect = new CoreGraphics.CGRect(100, 100, 1024, 768);

            window = new NSWindow(rect, style, NSBackingStore.Buffered, 
                                  false);
            window.Title = "WordBank Easy";
            window.TitleVisibility = NSWindowTitleVisibility.Hidden;
        }

        public override void DidFinishLaunching(
                                NSNotification notification)
        {
            Forms.Init();
            LoadApplication(new App());

            base.DidFinishLaunching(notification);
        }

        public override void WillTerminate(NSNotification notification)
        {
            // Insert code here to tear down your application
        }
    }
}

Happy coding!

Get the Most Out of iOS 11 with Visual Studio Tools for Xamarin

Join Craig Dunn explains what’s new in iOS 11 and how to take advantage of the latest updates – from drag-and-drop for iPad to machine learning and more – 100% in .NET and Visual Studio. Whether you’re building new or updating existing Xamarin.iOS apps, you’ll see how to implement new frameworks, APIs, and UI features, walk-through code samples, get expert tips and tricks, so you can start shipping iOS 11-ready apps to your users. In this webinar, you’ll:

  • Explore iOS 11 UI changes, including adapting to the iPhone X form factor
  • Dive into what .NET developers need to know about iOS 11
  • Add iOS 11 features to new and existing Xamarin apps with step-by-step examples
  • Ensure backwards compatibility with prior OS versions
  • Learn how to incorporate Azure Machine Learning tools into CoreML
  • Ask questions and receive guidance from our team of app experts

To develop for iOS 11, you'll need to have a machine that supports macOS Sierra and Xcode 9.

Download the source code of this video from GitHub.

What Singleton Pattern is in C# and its implementation

In another post I discussed how to implement Inversion of Control Pattern in C#. In this post I should explain what a singleton is.

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise, a second request for an instance but with a different parameter could be problematic.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version.

All these implementations share four common characteristics, however:

  • A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
  • The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
  • A static variable which holds a reference to the single created instance, if any.
  • A public static means of getting the reference to the single created instance, creating one if necessary.

First version - not thread-safe

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance=null;

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

This implementation is thread-safe. The thread takes out a lock on a shared object and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually, such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version - attempted thread-safety using double-check locking

// Bad code! Do not use!
public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

  • It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to the instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
  • Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe, but I'd rather not rely on that stronger semantics, especially if there's any doubt as to the safety. Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong!
  • It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
  • It still doesn't perform as well as the later implementations.

Fourth version - not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    // Explicit static constructor to tell C# compiler
    // not to mark type as beforefieldinit
    static Singleton()
    {
    }

    private Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}

As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

  • It's not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
  • There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
  • The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit.

One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical.

Fifth version - fully lazy instantiation

public sealed class Singleton
{
    private Singleton()
    {
    }

    public static Singleton Instance { get { return Nested.instance; } }
        
    private class Nested
    {
        // Explicit static constructor to tell C# compiler
        // not to mark type as beforefieldinit
        static Nested()
        {
        }

        internal static readonly Singleton instance = new Singleton();
    }
}

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Sixth version - using .NET 4's Lazy<T> type

If you're using .NET 4 (or higher), you can use the System.Lazy type to make the laziness really simple. All you need to do is pass a delegate to the constructor which calls the Singleton constructor - which is done most easily with a lambda expression.

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy =
        new Lazy<Singleton>(() => new Singleton());
    
    public static Singleton Instance { get { return lazy.Value; } }

    private Singleton()
    {
    }
}

It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property if you need that.

Structural code in C#

This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.

using System;

namespace PSC.Singleton
{
    class Program
    {
        /// <summary>
        /// MainApp startup class for Structural
        /// Singleton Design Pattern.
        /// </summary>
        static void Main(string[] args)
        {
            // Constructor is protected -- cannot use new
            Singleton s1 = Singleton.Instance();
            Singleton s2 = Singleton.Instance();

            // Test for same instance
            if (s1 == s2)
            {
                Console.WriteLine("Objects are the same instance");
            }

            // Wait for user
            Console.ReadKey();
        }

        /// <summary>
        /// The 'Singleton' class
        /// </summary>
        class Singleton
        {
            private static Singleton _instance;

            // Constructor is 'protected'
            protected Singleton()
            {
            }

            public static Singleton Instance()
            {
                // Uses lazy initialization.
                // Note: this is not thread safe.
                if (_instance == null)
                {
                    _instance = new Singleton();
                }

                return _instance;
            }
        }
    }
}

Real-world code in C#

This real-world code demonstrates the Singleton pattern as a LoadBalancing object. Only a single instance (the singleton) of the class can be created because servers may dynamically come on- or off-line and every request must go through the one object that has knowledge about the state of the (web) farm.

using System;
using System.Collections.Generic;

namespace PSC.Singleton
{
    class Program
    {
        /// <summary>
        /// MainApp startup class for Structural
        /// Singleton Design Pattern.
        /// </summary>
        static void Main(string[] args)
        {
            LoadBalancer b1 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b2 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b3 = LoadBalancer.GetLoadBalancer();
            LoadBalancer b4 = LoadBalancer.GetLoadBalancer();

            // Same instance?
            if (b1 == b2 && b2 == b3 && b3 == b4)
            {
                Console.WriteLine("Same instance\n");
            }

            // Load balance 15 server requests
            LoadBalancer balancer = LoadBalancer.GetLoadBalancer();
            for (int i = 0; i < 15; i++)
            {
                string server = balancer.Server;
                Console.WriteLine("Dispatch Request to: " + server);
            }

            // Wait for user
            Console.ReadKey();
        }

        /// <summary>
        /// The 'Singleton' class
        /// </summary>
        class LoadBalancer
        {
            private static LoadBalancer _instance;
            private List<string> _servers = new Listlt;string>();
            private Random _random = new Random();

            // Lock synchronization object
            private static object syncLock = new object();

            // Constructor (protected)
            protected LoadBalancer()
            {
                // List of available servers
                _servers.Add("ServerI");
                _servers.Add("ServerII");
                _servers.Add("ServerIII");
                _servers.Add("ServerIV");
                _servers.Add("ServerV");
            }

            public static LoadBalancer GetLoadBalancer()
            {
                // Support multithreaded applications through
                // 'Double checked locking' pattern which (once
                // the instance exists) avoids locking each
                // time the method is invoked
                if (_instance == null)
                {
                    lock (syncLock)
                    {
                        if (_instance == null)
                        {
                            _instance = new LoadBalancer();
                        }
                    }
                }

                return _instance;
            }

            // Simple, but effective random load balancer
            public string Server
            {
                get
                {
                    int r = _random.Next(_servers.Count);
                    return _servers[r].ToString();
                }
            }
        }
    }
}

Singleton real-world output

Advertsing

125X125_06

Planet Xamarin

Planet Xamarin

Calendar

<<  May 2018  >>
MonTueWedThuFriSatSun
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

View posts in large calendar

Month List