C# Primary Constructors

10/21/2024

Honestly, sometimes I just write these articles for my own reference. With C# being such a moving target, it helps to write about these in order to remind myself to start using them (once available).

Primary Construstors

Coming with C# 12 (which at the time I haven't started using yet), we will have access to Primary Constructors, and simple way to pass parameters to a Class and use them like member variables. The concept is pretty easy to see with this example:

public class Vector(double _dx, double _dy)
{
  public double Magnitude { get; } = Math.Sqrt(_dx*_dx+_dy*_dy);
  public double Direction { get; } = Math.Atan2(_dy, _dx);
}

In this example above, _dx and _dy essentially are member variables, and can be used as such. Which is why I prefixed them with an underscore (a common style guide).

If you want to have public properties in conjuction with these constructor parameters, that can be done like this:

public class Student(int id, string fullname)
{
  public int ID { get; } = id;
  public string Fullname { get; } = fullname;
}

During inheritance, these parameters can be passed along like this:

public class GraduateStudent(int id, string fullname) : Student(id, fullname)
{
  public int ID { get; } = id;
  public string Fullname { get; } = fullname;
}

So that's it. Pretty simple concept, and easy to use.


Please register or login to add a comment.

Comments (displaying 1 - 1):
No comments yet! Be the first...


  • C#/.NET
  • T-SQL
  • HTML/CSS
  • JavaScript/jQuery
  • .NET 8
  • ASP.NET/MVC
  • Xamarin/MAUI
  • WPF
  • Windows 11
  • SQL Server 20xx
  • Android
  • XBox
  • Arduino
  • Skiing
  • Rock Climbing
  • White water kayaking
  • Road Biking