Singleton snippet (PC/Mac) #XamarinMonth

lego island
Photo by Glen Carrie / Unsplash

I'm surprised nobody wrote about this obvious snippet, and I'm also surprised it hasn't been added to Visual Studio out of the box, but I'm going to share with you my snippet/template for the Singleton design pattern.

Thanks to Luis Matos (@luismatosluna) for organising this Xamarin Month on the topic of Code Snippets! Check out the twitter hashtag to find more posts or see the monthly calendar of all posts here.

What are snippets/templates ?

Code Snippets (or templates in the Visual Studio for Mac world) are ready-made snippets of code you can quickly insert into your code. For example, the for code snippet creates an empty for loop.

More about Snippets in the docs.

How to install

It's very simple to install, here are the options :

  • Recreate the snippets on your machine, feel free to copy paste and customise 😉
  • (PC) Save singleton.snippet into %USERPROFILE%\Documents\Visual Studio 2019\Code Snippets\Visual C#\My Code Snippets
  • (Mac) Save singleton.template.xml into ~/Library/VisualStudio/8.0/Snippets

How to use

While in a class, type "singleton" and double-tap on tab and .. Magic!

You'll get a class that looks like this :

namespace SnippetProject
    public class MySuperClass
        #region Singleton

        private static MySuperClass _instance;

        public static MySuperClass Current => _instance ??= new MySuperClass();


        private MySuperClass()
            // TODO : Delete other constructors
            // TODO : Make MySuperClass sealed

The code

For some reasons the Template for Visual Studio for mac didn't allow me to reuse the same variable (with the function GetCurrentClassName() ) twice. This is why I had to go dirty ... Let me know if you know a workaround.

Let me know in the comments or on Twitter if it helped you 🙂