Sharplab.io
Since .NET 8 is released medio 14th of November, 2023, which is like in two weeks after writing this article, it will be generally available very soon. You can already also use .NET 8 in preview versions of VS 2022. Let's look at usage of primary constructor. The following program defined one primary constructor, note that the constructor is before the class declaration starts inside
the block. Program.cs
using System;
public class Person(string firstName, string lastName) {
public override string ToString()
{
lastName += " (Primary constructor parameters might be mutated) ";
return $"{lastName}, {firstName}";
}
}
public class Program {
public static void Main(){
var p = new Person("Tom", "Cruise");
Console.WriteLine(p.ToString());
}
}
The output of running the small program above gives this output :
Program.cs
Cruise (Primary constructor parameters might be mutated) , Tom
If a class has added a primary constructor, this constructor must be called. If you add another constructor, you must call the primary constructor. For example like in this example, using a default constructor (empty constructor), calling the primary constructor:
public Person() : this("", "")
{
}
A gist of this can be tested here :
https://sharplab.io/#gist:494a321789363cdef9518278e14fb311Another example of primary constructors are shown below. We use a record called Distance and pass in two dx and dy components of a vector and calculate its mathematical
distance and direction. We convert to degrees here using PI * radians = 180 expression known from trigonometry. If dy < 0, we are in quadrant 3 or 4 and we add 180 degrees.
using System;
var vector = new Distance(-2, -3);
Console.WriteLine($"The vector {vector} has a magnitude of {vector.Magnitude} with direction {vector.Direction}");
public record Distance(double dx, double dy) {
public double Magnitude { get; } = Math.Round(Math.Sqrt(dx*dx + dy*dy), 2);
public double Direction { get; } = dy < 0 ? 180 + Math.Round(Math.Atan(dy / dx) * 180 / Math.PI, 2) :
Math.Round(Math.Atan(dy / dx) * 180 / Math.PI, 2);
}
A copy of the code above is available in the Gist below:
https://sharplab.io/#gist:78092029741a7b9e7362441d9eb8e083
The vector Distance { dx = -2, dy = -3, Magnitude = 3.61, Direction = 236.31 } has a magnitude of 3.61 with direction 236.31
If you have forgot trigonometry lessons from school, here is a good page about magnitude and direction:
https://mathsathome.com/magnitude-direction-vector/
No comments:
Post a Comment