Learning C# 9 Init Only Property Is Not Difficult at All!

In this article, I will show you one of the new features of C# 9 init only property.
You can use a ‘init’ accessor instead of an set accessor to declare a property in C# 9. Only an object’s initializer can set init-only properties, which are generally read-only:

You can create large immutable classes with init-only properties rather than the anti-pattern of writing a method with many optional parameters.

Let’s understand the property with one example. Consider the following class as you can see in the following code I am using init instead of private set

public class Blog{

	public string Title { get; init; } //init-only
	public string Description { get; init;} //init-only


var blog = new Blog { Title = "C# 9 New Feature", Description = "C# init create read only property" };
Console.WriteLine(blog); // It will print the output to console

As you can see in the above example that I am initializing the property in the object initializer, But if you try to set the value of Title the property will throw an error.

blog.Title="Some other title"; 

It will give you the following error.

CS8852 Init-only property or indexer ‘Blog.Title’ can only be assigned in an object initializer, or on ‘this’ or ‘base’ in an instance constructor or an ‘init’ accessor.{alertError}

You can set ==init == only property in constructor.

Another place you can set the value of the only property is the constructor of the class.

var newBlog=new Blog{Description="New Description"};

public class Blog
	public string Title { get; init; } //init-only
	public string Description { get; init; } //init-only
	public Blog()
		Title="Title From Constructor";

Next Post Previous Post
No Comment
Add Comment
comment url