Primary Constructor in C# 12
Sample code without Primary constructor
Section titled βSample code without Primary constructorβRabbit.cs
using static System.Console;namespace WithoutPrimaryConstructor{ internal class Rabbit { public string Name { get; set; } public int Age { get; set; } public double Weight { get; set; } public string Color { get; set; } public string Breed { get; set; } public bool IsDomesticated { get; set; }
public Rabbit(string name, int age, double weight, string color, string breed, bool isDomesticated) { Name = name; Age = age; Weight = weight; Color = color; Breed = breed; IsDomesticated = isDomesticated; }
//Method to print the rabbit's properties public void Print() { //print the string WriteLine($"Name: {Name}"); WriteLine($"Age: {Age}"); WriteLine($"Weight: {Weight}"); WriteLine($"Color: {Color}"); WriteLine($"Breed: {Breed}"); WriteLine($"IsDomesticated: {IsDomesticated}"); } }}
Program.cs
using WithoutPrimaryConstructor;Rabbit rabbit = new Rabbit("Bugs", 2, 2.5, "Brown", "Holland Lop", true);rabbit.Print();
Sample code with Primary constructor
Rabbit.cs
using static System.Console;
namespace BankyCSharp12Code{ internal class Rabbit(string name, int age, double weight, string color, string breed, bool isDomesticated) { public string Name { get; set; } = name; public int Age { get; set; }= age; public double Weight { get; set; } = weight; public string Color { get; set; } = color; public string Breed { get; set; } = breed; public bool IsDomesticated { get; set; } = isDomesticated;
//Method to print the rabbit's properties public void Print() { //print the string WriteLine($"Name: {Name}"); WriteLine($"Age: {Age}"); WriteLine($"Weight: {Weight}"); WriteLine($"Color: {Color}"); WriteLine($"Breed: {Breed}"); WriteLine($"IsDomesticated: {IsDomesticated}"); } }}
Program.cs
using BankyCSharp12Code;Rabbit rabbit = new Rabbit("Bugs", 2, 2.5, "Brown", "Holland Lop", true);rabbit.Print();