I'm reading some data from an XML format and putting it in my classes and am just wondering what the best practice is regarding fields that can be empty and, if they are empty, have a default value. Values that haven't been supplied don't need to be written back to the file.
I was thinking of using nullable types, however, what's the best way in code of specifying a default value (though I wouldn't need a default value for every field as not all fields have a specified default value or the default value is 0)
At the moment I'm using this:
class SomeElement
{
public const int DefaultFoo = 123;
public int? Foo { get; set; }
}
but don't know if the following would be more obvious:
class SomeElement
{
// Setting HasFoo to false will set Foo to the default value
public bool HasFoo { get; set; }
// Setting Foo to anything will set HasFoo to true
public int Foo { get; set; }
}
As some of the classes have lots of properties, the second option will create lots more methods in the classes, however, might be easier to use if you don't care whether Foo has a value or not.
The final alternative might be using either a static method in the base class or an extension method to make the default easier to get (idea based on this)
// In some method using the class
int value = SomeElementBase.GetValueOrDefault(() => myObj.Foo);
// or an extension method
int value = myObj.GetValueOrDefault(x => x.Foo);
I'd still supply the DefaultFoo
fields but the static/extension method might make it easier to access?
What are your thoughts? Has anybody come across this problem before? Should I just use default values and when saving back to the file omit fields that equal their default value?