Friday, May 5, 2023

Primary Constructor - C# 12

Primary constructor allows you to add parameters to calss declaration itself and use these values in class body. Promary constructor was introduced for records in C#9. C#12 extends it to all classes and structs.

c sharp primary constructor

A class with a primary constructor can have additional constructors. Additional constructors must use a this(…) initializer to call another constructor on the same class. This ensures that the primary constructor is always called and all the all the data necessary to create the class is present.

public class Student(int id, string name, IEnumerable<string> subjects)
    {
        public Student(int id, string name) : this(id, name, Enumerable.Empty<string>()) { }
        public int Id => id;
        public string Name { get; set; } = name;
        public IEnumerable<string> Subjects => subjects;
    }

Find out more in the What is new in C#12.

No comments:

Post a Comment

^ Scroll to Top