'C# Declaring class type in list object is not using default parameter value?
When the Orders class is getting initialized, the default constructor in order gets called but Initialized has a false value instead of true even though no parameter is passed. I seem to not understand this behavior at all.
public class Orders
{
[JsonProperty("Objects")]
public List<Order> Items { get; set; } = new List<Order>();
}
public class Order
{
public Order(bool _initialize = true)
{
if (_initialize)
{
this.Cr = 0;
this.User = Guid.Empty;
}
}
Solution 1:[1]
The default constructor of Order does not get called when Orders.Items is initiazed. Only an empty list is created.
Also Order(bool _initialize = true) is not the default constructor because it has one argument specified (even though it is optional).
To create this functionality and define a default constructor you need two definitions
public Order()
{
// default values
}
public Order(bool _initialize) : this()
{
if (_initialize)
{
// specific values
this.Cr = 0;
this.User = Guid.Empty;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John Alexiou |
