Codementor Events

What the hell is this odd init keyword?

Published Jun 28, 2023
What the hell is this odd init keyword?

Cross-posted from my personal blog.

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.

  • ✅ private set
  • ✅ readonly
  • ✅ init
public GuineaPig(string propertyWithPrivateSet, string propertyReadonly, string propertyWithInit)
{
    PropertyWithPrivateSet = propertyWithPrivateSet;
    PropertyReadonly = propertyReadonly;
    PropertyWithInit = propertyWithInit;
}
  • ✅ private set
  • ❌ readonly
  • ❌ init
// This method is inside the GuineaPig class
public void EraseProperties() 
    => PropertyReadonly = PropertyWithInit = PropertyWithPrivateSet = string.Empty;
  • ✅ private set
  • ❌ readonly
  • ✅ init
public GuineaPig Breed()
{
    return new GuineaPig()
    {
        PropertyWithPrivateSet = string.Empty,
        PropertyWithInit = string.Empty,
        PropertyReadonly = string.Empty
    };
}
  • ❌ private set
  • ❌ readonly
  • ✅ init
var firstPig = new GuineaPig()
{
    PropertyWithPrivateSet = string.Empty,
    PropertyWithInit = string.Empty,
    PropertyReadonly = string.Empty
};

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.

Discover and read more posts from Henrique Dalcin Dalmas
get started
post commentsBe the first to share your opinion
Show more replies