c# - Using code contracts in one property to provide hints about another property -
i have struct
(simplified brevity):
public struct period { public datetime? start { get; private set; } public datetime? end { get; private set; } public bool ismoment { { return this.start.hasvalue && this.start == this.end; } } public period(datetime? start, datetime? end) : this() { this.start = start; this.end = end; } public override string tostring() { return this.ismoment ? this.start.value.tostring("g") : string.format("{0:g} – {1:g}", this.start, this.end); } }
everything works fine, resharper showing warning on this.start.value.tostring
:
possible '
system.invalidoperationexception
'
if copy body of ismoment
property condition, warning goes away, i'd able reuse property. can disable resharper warning comment (which have done moment), or changing tostring
string.format
, have handful of other places in code , got me thinking. i'd try resolve using code contracts, unfortunately don't have whole lot of experience code contracts , i'm not sure how look.
is there anyway use code contracts indicate resharper if ismoment
true
, start
not null
?
do in ismoment:
contract.ensures(result == false || start <> null);
(that's not right. i'm typing on phone.)
update:
the problem due possibility of multithreaded code changing value of start between ismoment test , start.value evaluation.
it may more correct copy value local variable cannot modified other threads.
public override string tostring() { period local = this; return local.ismoment ? local.start.value.tostring("g") : string.format("{0:g} – {1:g}", local.start, local.end); }
this looks unnecessary work, , may inefficient, more "correct". if struct small, though, may more efficient in many cases.
Comments
Post a Comment