Allow field or property values to be assigned directly from the constructor parameters #7670
-
I would like to be able to assign fields and properties in the constructor directly from the parameters. I know that a primary constructor can be a good solution, but sometimes we can't use a primary constructor (for example, when we need to add the
This feature was also implemented in Dart with the same syntax:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Records or primary constructors with #3650 / #7047 seem like they would solve this issue in a better way IMO. |
Beta Was this translation helpful? Give feedback.
-
As of next week, with the release of .NET 8 and C# 12, you will be able to use primary constructors to express that as: public class Car(string brand, string model, string color, decimal price)
{
public string Brand { get; set; } = brand;
public string Model { get; set; } = model;
public string Color { get; set; } = color;
public decimal Price { get; set; } = price;
} If you have concerns over this feature, such as the ability to use Json attributes, or you'd prefer to eg be able to express that as: public class Car(
string Brand { get; set; },
string Model { get; set; },
string Color { get; set; },
decimal Price { get; set; }) Then head over to #7667 and request it there as Microsoft are actively asking for feedback on this feature. |
Beta Was this translation helpful? Give feedback.
As of next week, with the release of .NET 8 and C# 12, you will be able to use primary constructors to express that as:
If you have concerns over this feature, such as the ability to use Json attributes, or you'd prefer to eg be able to express that as:
Then head over to #7667 and r…