Property initializers in C# were introduced with version 6.0, adding a convenient way to initialize properties of a class. With this feature, we can assign default values to properties directly in the class definition without the need for constructor logic or additional methods.
This helps make code more concise, readable, and manageable, particularly in simple data models or classes with multiple properties that need default initialization.
An init accessor is a property initializer that defines an accessor method to assign a value to a property or indexer element in the object being created. The init keyword enforces immutability, so once an object is initialized it cannot be changed.
Following is the basic declaration of the property initializer:
csharppublic class ClassName { public PropertyType PropertyName { get; set; } = defaultValue; }
Here, in the above code declaration, PropertyType is the type of the property, PropertyName is the name of the property, and defaultValue is the value assigned at initialization.
In this example, consider a basic Person class with properties like FirstName, LastName, and Age. Traditionally, you would initialize these properties in the constructor, but with the properties initializer, we can assign default values directly.
csharpusing System; public class Person { public string FirstName { get; set; } = "Aman"; public string LastName { get; set; } = "Gupta"; public int Age { get; set; } = 25; } public class Program { public static void Main() { Person person = new Person(); Console.WriteLine($"Name: {person.FirstName} {person.LastName}, Age: {person.Age}"); } }
Output
Let’s look at an example where we initialize a list of string values: Property initializers can also be used with more complex types, such as objects or collections.
csharpusing System; using System.Collections.Generic; public class ShoppingCart { public List<string> Items { get; set; } = new List<string> { "Apple", "Banana", "Milk" }; public decimal TotalPrice { get; set; } = 0.0m; } public class Program { public static void Main() { ShoppingCart cart = new ShoppingCart(); Console.WriteLine("Items in the cart:"); foreach (var item in cart.Items) { Console.WriteLine(item); } Console.WriteLine($"Total Price: {cart.TotalPrice}"); } }
Output
Copyrights © 2024 letsupdateskills All rights reserved