Update: C# 9 should fix this problem using records :D
I was wondering if there is a recommended approach to initializing the properties of a plain object that is used for data transfer, for example via a REST-API.
Here are two variants I can think of:
public class Dto
{
public string Name { get; set; }
public int Number { get; set; }
}
new Dto {
Name = actualName,
Number = actualNumber
};
vs
public class Dto
{
public string Name { get; private set; }
public int Number { get; private set; }
public Dto(string name, int number)
{
Name = name;
Number = number;
}
}
new Dto(actualName, actualNumber);
or
new Dto(name: actualName,
number: actualNumber);
I would go for the first, since it's shorter and requires less work to maintain. However, newly added properties could be overlooked by someone filling the DTO. I am also aware that it does not make the object immutable, but since it's only a DTO I personally find that to be less important.