When creating a simple data container class, what should it be?
- Class or struct?
- Mutable or immutable?
- With or without non-empty constructor?
Examples of the above:
struct MutableStruct
{
public string Text { get; set; }
public int Number { get; set; }
}
struct ImmutableStruct
{
public string Text { get; private set; }
public int Number { get; private set; }
public ImmutableStruct(string text, int number)
: this()
{
Text = text;
Number = number;
}
}
struct MutableStructWithConstructor
{
public string Text { get; set; }
public int Number { get; set; }
public MutableStructWithConstructor(string text, int number)
: this()
{
Text = text;
Number = number;
}
}
class MutableClass
{
public string Text { get; set; }
public int Number { get; set; }
}
class ImmutableClass
{
public string Text { get; private set; }
public int Number { get; private set; }
public ImmutableClass(string text, int number)
{
Text = text;
Number = number;
}
}
class MutableClassWithConstructor
{
public string Text { get; set; }
public int Number { get; set; }
public MutableClassWithConstructor(string text, int number)
{
Text = text;
Number = number;
}
}
Any good reasons we should choose one above another? Or are there mostly subjective preferences that separate them? Or does it depend a lot on the spesific use cases? If so in what use cases should you choose what and why?
ImmutableStruct
andImmutableClass
aren't truly immutable: The properties have private setters but their state can be changed from within the struct/class itself. (This is a shortcut that I often use myself, but it would be better to avoid the auto-property and use a readonly member variable instead, exposed via a public getter.) – Deinapublic string Text { get; }
should create a readonly backing field and enable setting in constructor only, like with readonly fields. At the moment I think that line creates a useless property returning null... – Cropdustingprivate readonly string _Text; public string Text { get { return _Text; } }
. It's a shame that you can't mark a property asreadonly
, maybe in some future version of C#, but I wouldn't bet on it. – Deina