I read some data from the XML format and put it in my classes, and I'm just wondering what is best for fields that can be empty and, if empty, have a default value. Values that were not provided do not need to be written back to the file.
I was thinking about using types with a null value, however, which is the best way in the code to determine the default value (although I do not need a default value for each field, since not all fields have a default value set or default value 0)
I am currently using this:
class SomeElement { public const int DefaultFoo = 123; public int? Foo { get; set; } }
but I don’t know if the following will 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; } }
Since some classes have many properties, the second option will create a lot more methods in classes, however it might be easier to use if you don't care if Foo matters.
The final alternative can be either a static method in the base class, or an extension method to make it easier to get by default (the idea is based on this )
I would still supply DefaultFoo fields, but could the static / extension method make access easier?
What are your thoughts? Has anyone encountered this problem before? Should I just use the default values and omit the fields equal to their default values when saving back to the file?
source share