✅ Required Member must be set in the object initializer or attribute constructor

new PresetDataModel(preset)
new PresetDataModel(preset)
give a compile error
Severity Code Description Project File Line Suppression State
Error CS9035 Required member 'PresetDataModel.Name' must be set in the object initializer or attribute constructor.
Severity Code Description Project File Line Suppression State
Error CS9035 Required member 'PresetDataModel.Name' must be set in the object initializer or attribute constructor.
the class in question
public class PresetDataModel
{
public PresetDataModel(ToppingPreset preset)
{
Id = preset.Id;
Name = preset.Name;
foreach(var topping in preset.Toppings)
{
ToppingToValuePairs.Add(new ToppingToValuePair()
{
ToppingId = topping.ToppingId,
ToppingValueId = topping.ToppingValueId,
});
}
}
public Guid Id { get; set; }
public required string Name { get; set; }
public List<ToppingToValuePair> ToppingToValuePairs { get; set; } = new List<ToppingToValuePair>();

}
public class PresetDataModel
{
public PresetDataModel(ToppingPreset preset)
{
Id = preset.Id;
Name = preset.Name;
foreach(var topping in preset.Toppings)
{
ToppingToValuePairs.Add(new ToppingToValuePair()
{
ToppingId = topping.ToppingId,
ToppingValueId = topping.ToppingValueId,
});
}
}
public Guid Id { get; set; }
public required string Name { get; set; }
public List<ToppingToValuePair> ToppingToValuePairs { get; set; } = new List<ToppingToValuePair>();

}
if my constructor sets it, why do I get the compile error? Is there some way to avoid besides the following
new PresetDataModel(preset) { Name = preset.Name }
new PresetDataModel(preset) { Name = preset.Name }
4 Replies
333fred
333fred2mo ago
Don't mark the property with required if the only constructor on the type is going to set it The point of required is to shift the responsibility of initializing a property to the person using the constructor If there's only one constructor, and it takes care of it, then you don't need required
KakuregaRamen
KakuregaRamen2mo ago
I see thanks
333fred
333fred2mo ago
You're welcome. If you have any other questions about required feel free to ask, otherwise you can go ahead and $close this thread 🙂
MODiX
MODiX2mo ago
If you have no further questions, please use /close to mark the forum thread as answered
Want results from more Discord servers?
Add your server
More Posts