Understanding C# Init-Only Properties and Their Distinction from Set Properties

In the world of C# programming, new features keep popping up to make coding better and easier. One cool thing that came with C# 9 is “init-only” properties. These properties change how we handle values in objects. In this blog post, we’ll look at init-only properties with an example and see how they’re different from regular “set” properties.

Init-Only Properties

In our example, we have a Person class with three init-only properties: FirstName, LastName, and Age. The special part is the init keyword. It only lets us change properties when we create the object. After that, we can’t change them. This helps make our code safer.

class Person
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
    public int Age { get; init; }
}

Trying It Out

But how does this work? In the Program class, we make a new Person named person. We set its FirstName, LastName, and Age when we create it.

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person
        {
            FirstName = "John",
            LastName = "Doe",
            Age = 30
        };

        Console.WriteLine($"Name: {person.FirstName} {person.LastName}, Age: {person.Age}");
    }
}

How init Is Different from set

Now, let’s break down the main differences between init-only properties and regular set properties:

  1. Flexibility: With set properties, we can change values anytime after creating the object. But with init-only, we can only set values during object creation.

  2. Safety and Immutability: Init-only properties are safer because they stop accidental changes once the object is made. Set properties can change, which might cause unexpected issues.

  3. Clear Intent: Init-only properties clearly show they won’t change after creation. Set properties don’t make this as clear.

  4. When to Use: Init-only properties are great when we really need to keep the object’s info safe. This is useful for things like data we’re sending, settings, and unchanging data.

To Wrap Up

C# 9’s init-only properties are a big help for making our code safer and easier to understand. By using the init keyword, we lock down properties after creating an object. This stops us from accidentally messing things up later. Remember, init-only properties are different from set properties because they’re safer, show clear intent, and are perfect for special cases where we need to keep things from changing. This new way of thinking and coding in C# can make our programs stronger and more dependable.

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post