Well ... the "best" answer (very stubborn, but I mean) is when you do not need to distinguish between the two, because there is only one possible state: p>
class MyModel { public int Id {get; private set;} public string Title {get; private set;} public DateTime CreatedDate {get; private set;} public bool IsActive {get; private set;} Public MyModel(int Id, string Title, DateTime CreatedDate, bool IsActive) { this.Id = Id; this.Title = Title; this.CreatedDate = CreatedDate; this.IsActive = IsActive; } }
I know that this is not always possible, for example Query by Example.
The use of "magic numbers" such as "Setting the ID value to 0 makes sense ..." is usually avoided. Once you do this, each piece of code you write must be encoded to know what the magic number is and what they mean. This is rarely achieved and is full of nasty looking and error prone code.
If you just SHOULD have a distinction between a field that matters and not, your later example is a little better. At least here you value types are explicitly valid or invalid. However, using Nullable <T> means that you must use another tool to determine if a class, string, or other reference type is invalid.
IMO, you are better off with the following, although this is becoming very verbose, as you will see.
class MyModel { private int _id; public bool HasId { get; set; } public int Id { get { if (!HasId) throw new System.InvalidOperationException(); return _id; } set { HasId = true; _id = value; } } private string _title; public bool HasTitle { get; set; } public string Title { get { if (!HasTitle) throw new System.InvalidOperationException(); return _title; } set { if (value == null) throw new System.ArgumentNullException("Title"); HasTitle = true; _title = value; } } private DateTime _createdDate; public bool HasCreatedDate { get; set; } public DateTime CreatedDate { get { if (!HasCreatedDate) throw new System.InvalidOperationException(); return _createdDate; } set { HasCreatedDate = true; _createdDate = value; } } private bool _isActive; public bool HasIsActive { get; set; } public bool IsActive { get { if (!HasIsActive) throw new System.InvalidOperationException(); return _isActive; } set { HasIsActive = true; _isActive = value; } } }
Finally, if you go this route, the code generator will serve you well.
csharptest.net
source share