What the hell is this odd init keyword?


What the hell is this odd init keyword?

luffy confused with the init keyword

Getting up to date with the new C# features can be tricky. Not everyone is used to reading the change logs (pro tip: you should). Others do, but forget soon after, since it’s not really simple to change the way we usually code. The init keyword is not exactly new, it came in C# 9.0, but not everyone is familiar with it. So what does it do? Let’s check Microsoft’s definition:

An init-only setter assigns a value to the property or the indexer element only during object construction.

But what does it really means? Let’s create a simple small application and see when we can use the different accessors.

Constructor

  • ✅ private set
  • ✅ readonly
  • ✅ init
public GuineaPig(string propertyWithPrivateSet, string propertyReadonly, string propertyWithInit)
{
    PropertyWithPrivateSet = propertyWithPrivateSet;
    PropertyReadonly = propertyReadonly;
    PropertyWithInit = propertyWithInit;
}

Assigning new values

  • ✅ private set
  • ❌ readonly
  • ❌ init
// This method is inside the GuineaPig class
public void EraseProperties() 
    => PropertyReadonly = PropertyWithInit = PropertyWithPrivateSet = string.Empty;

Object initializer within the class

  • ✅ private set
  • ❌ readonly
  • ✅ init
public GuineaPig Breed()
{
    return new GuineaPig()
    {
        PropertyWithPrivateSet = string.Empty,
        PropertyWithInit = string.Empty,
        PropertyReadonly = string.Empty
    };
}

Object initializer outside the class

  • ❌ private set
  • ❌ readonly
  • ✅ init
var firstPig = new GuineaPig()
{
    PropertyWithPrivateSet = string.Empty,
    PropertyWithInit = string.Empty,
    PropertyReadonly = string.Empty
};

Conclusion

A property with the init keyword accessor can, as the name suggests, be used during the creation of an object. The main advantage over the private set accessor is that it allows us to use the object initializer for that property anywhere in our code. It is also more flexible than the readonly accessor since you can only set it during the constructor. It is a great tool to have in your pocket, so keep it in mind next time you plan on doing some refactoring. Not confident in your refactoring skills? We got you covered.