Immutable Models in MVVM

10-22-04 025
Source: flickr/ Jeff Attaway


The first M stands for Model – an implementation of the application’s domain model that includes a data model along with business and validation logic. Examples of model objects include repositories, business objects, data transfer objects (DTOs), Plain Old CLR Objects (POCOs), and generated entity and proxy objects.

definition source


In object-oriented and functional programming, an immutable object(unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.

definition source

Why bother?

Imagine the next simple situation, your application downloads a JSON,  deserialises it to an object and then presents the downloaded data. You would expect the downloaded data to be one-to-one to the data on the remote server, however the data can be accidentally or intentionally mutated.

Here is an example of a mutable Model:

public class MyMutableObject
    public long Id { get; set; }
    public string Title { get; set; }
    public List<string> Contents { get; set; }

All the properties has public setters which means that any of those can be changed after the object creation. Even if we make all the setters private, it could be still possible to manipulate data within the List.

Here is an example of immutable Model:

public sealed class MyImmutableObject
    public long Id { get; }
    public string Title { get; }
    public IReadOnlyCollection<string> Contents { get; }

    public MyImmutableObject(
        long id,
        string title,
        IReadOnlyCollection<string> contents)
        Id = id;
        Title = title;
        Contents = contents;

There are no public setters available and mutable collection type is replaced by “immutable” one. There is no option to extend this class as well as changing the data after the object is created.

IReadOnlyCollection is not a real immutable collection but an immutable facade. It is not thread safe and possible to cast to IList and try to manipulate the collection, however System.NotSupportedException will be thrown.

Alternatively we can add a System.Collections.Immutable NuGet package and replace IReadOnlyCollection<T> by IImmutableList<T> if we want a real immutable collection.

JSON Deserialization

Often Models used for deserialization and it can be tricky to deserialize JSON to immutable object. Luckily with Json.NET it is not an issue. We can easily serialize and deserialize MyImmutableObject:

var myImmutableObject = new MyImmutableObject(
        id: 1,
        title: “Test”,
        contents: new List<string> { “One”, “Two”, “Three” });
var json = JsonConvert.SerializeObject(myImmutableObject);
var deserializedObject = JsonConvert.DeserializeObject<MyImmutableObject>(json);

Please note that if your Model has more than one constructor you will need to mark  one for deserialization explicitly,  by adding a JsonConstructor attribute.


With .NET Standard we can use EntityFramework Core in our Xamarin.Forms applications which is great! And it is great twice since we can have a code first  immutable model fully supported by EF.


public sealed class ToDoModel
    public int Id { get; private set; }
    public string Title { get; private set; }
    public string Notes { get; private set; }
    public DateTimeOffset CreatedAt { get; private set; }
    public DateTimeOffset? UpdatedAt { get; private set; }

    ToDoModel() { /* EF requires a parameterless constructor. */ }

    public ToDoModel(
        int id,
        string title,
        string notes,
        DateTimeOffset createdAt,
        DateTimeOffset? updatedAt)
        Id = id;
        Title = title;
        Notes = notes;
        CreatedAt = createdAt;
        UpdatedAt = updatedAt;

When using an “immutable” Model with EF keep in mind:

  • Parameterless constructor – is required, should be private.
  • Setters – are required, should private.
  • Object tracking – should be disabled.


  • SQLite.NET did not work properly with private constructor and setters.
  • We have to count with private setters since it is still possible to change a value with a private setter within the same class.


In this blogpost we discussed how to make immutable Models and checked few common scenarios. I would recommend to start immutable and change to mutable if necessary. Here are few recommendations to keep in mind:

  • Forget about private setters: prop -> propg
  • Make publicly available properties readonly
  • Use constructors
  • Seal classes
  • Use immutable collections or at least IReadOnlyCollection<T>
  • The goal is not to get 100% immutability but to improve code quality

Immutability is a very interesting topic which has pros and cons. For example it may harm performance or introduce unnecessary complexity in some cases, so use it wisely. There are few great resources that I would recommend to get familiar with:



Archiving your code



Title of this blog post may sound very weird in 2018 while github / vsts / bitbucket are still up and running. However, it still seems to be very common to archive your solution and upload it to cloud or send it by email. Don’t ask me why, it is just still there.

The most painful and annoying mistake you can make is to include dependencies that can be easily downloaded or compiled code. Painful because it may significantly increase the size of the archive and annoying because you may have to download it for hours because of it. Continue reading “Archiving your code”

Visual Studio for Mac tips & tricks

Switching from old good VS (for Windows) to a new cool VS for Mac can be painful. Original VS was released in 1997 (according to wikipedia) while VS for Mac was released only in 2016. Yes, it is based on XamarinStudio which is built on MonoDevelop but it still has a long way to go in order to be close to it’s ancient relative.

In this article we will take a look on VS for Mac “hidden gems” that can optimize and smooth your workflow. All you have to do is to open Mac’s VS Preferences and read this article on the side.



One of the very basic yet very important settings is the Font. While there is nothing bad using the default font, FiraCode could beautify your code and improve it’s readability by replacing sequences of characters by a single ligature.

The project repository on github contains detailed information on how to install it in your system. It’s also great because this font can be used almost everywhere.

Continue reading “Visual Studio for Mac tips & tricks”

User input validation in Xamarin.Forms

This slideshow requires JavaScript.

One of the very common tasks that any mobile developer meets is validation of the user input. It can be an email, password complexity, length, not empty or any other sort of input validation. In this article we will try to find an appropriate light-weight and reusable solution, so let’s start!

Continue reading “User input validation in Xamarin.Forms”

Firebase authentication in Xamarin.Forms

Firebase Authentication (vert, light)

Integrating Firebase Auth in Xamarin.Forms is very easy and basic authentication flow implementation can be achieved under 20 lines of code. There is more work with settings than code writing. In this article we will:

  1. Configure Firebase app
  2. Create Xamarin.Forms application to authenticate users via Firebase Auth
  3. Create a .NET Core WEB API project to validate Firebase Auth token and return simple data

Continue reading “Firebase authentication in Xamarin.Forms”

Automatically converting PCL to .NET Standard 2.0 project

Mar-23-2018 01-41-34

Every time you create a new Xamarin.Forms project  in Visual Studio for Mac you have to manually convert it to .NET Standard. The conversion is very straightforward and can be done with just a few steps:

Hopefully one day VS team will take care of it, till then, I decided to automate this process and created an add-in/extension for VS for Mac – Mutatio.

Mutatio – in Latin means change, transformation or exchange.

Mutatio can convert newly created or existing projects. Please keep in mind that there might be NuGet packages that does not support .NET Standard 2.0, in this case you may see related exceptions.

In case you change your mind and you want to rollback, Mutatio is making a backup of all the files it modifying and deleting under the project’s root directory within mutatio_backup folder. So all you have to do is to copy the files back to your project and reload the solution.

One of the biggest challenges I met while development was related to reloading the project after conversion. Within VS for Mac after manually modifying the *.csproj under the right click menu of the project there will appear a Reload option, however I didn’t find a way to call this method programatically. Currently, the whole solution will be reloaded as a workaround. If you know how to solve the problem programatically I would really appreciate if you will share your knowledge by contributing or leaving a comment.

More details can be found on GitHub.

Reducing the amount of code by switching to .NET Standard

What can feel better than writing a code? Of course deleting it!

There are many good technical articles that explain why .NET Standard is great and why should we use it. My goal in this article is to demonstrate some benefits in practice.

If you didn’t switch yet from PCL and Shared Projects to .NET Standard, I would highly recommend to do it. Most of the third party libraries are compatible and the switch is usually painless. After switching to .NET Standard you could benefit from reducing the code size and the amount of “hacks”. Let’s take a look on few practical examples. Continue reading “Reducing the amount of code by switching to .NET Standard”