C# 12 primary constructors
A concise syntax to declare constructors whose params are available anywhere in the body.
Primary constructors is an easier way to create a constructor for your class or struct, by eliminating the need for explicit declarations of private fields and bodies that only assign param values.
They are great when you just need to do simple initialization of fields and for dependency injection.
Code example using primary constructors
public class Book(int id, string title, IEnumerable<decimal> ratings)
{
public int Id => id;
public string Title => title.Trim();
public int Pages { get; set; }
public decimal AverageRating => ratings.Any() ? ratings.Average() : 0m;
}
another example
public class Person(string firstName, string lastName)
{
public string FirstName { get; } = firstName;
public string LastName { get; } = lastName;
}