within class property cannot set embedded struct's property

B

Ben Voigt [C++ MVP]

Peter Duniho said:
[...]
I'm talking about this (to steal your example):

if (dt.HasValue)
{
dateTimePicker1.Value = dt.GetValueOrDefault();
}
else
{
dateTimePicker1.Enabled = false;
}

After I've checked HasValue, I prefer to just pull the value from the
field directly. GetValueOrDefault accomplishes this, while reading the
Value property does an extra test for null which I know will NEVER be
meaningful (unless the value is being accessed from another thread
without synchronization -- yuck! plus reading the Value property
doesn't eliminate that sort of race anyway)

Okay, so now I do understand what you mean. I can't say that it seems
like a meaningful optimization to me, and it just clutters up the code in
my view. But that's certainly a subjective matter. In any case, I do

I think that it's counter-intuitive that reading Value should be more
complicated than calling GetValueOrDefault -- both the choice of property vs
method and the naming suggest that GetValueOrDefault is more complex -- but
get_Value actually calls GetValueOrDefault internally. I would have
preferred to see GetValueOrDefault made into the Value getter, and rename
the current Value implementation as SafeValue or CheckedValue. Or even
changing GetValueOrDefault into a RawValue field or property would be good,
as long as it's immediately clear which is direct access to the value and
which carries the complicated semantics.
still fail to see how any of this applies to the question that started all
this; namely, whether having a way to protect against reading a Value
field that shouldn't be usable is a useful feature of Nullable<T> or not.

I still maintain that it is. Just because one _can_ use the
GetValueOrDefault() optimization, that doesn't mean that everyone does,

I think that 99% of the time when the optimization is not used, it is
because of poor API design and not because the Value getter behavior is
desirable.
nor does it mean that the class can provide the same semantics as it does
now if the Value member was a public field instead of a property.

I think that the checked Value is not a bad thing, it just shouldn't be the
usual use of Nullable<T> and the naming should reflect this. There could be
both a public readonly field (or really lightweight property) and a heavy
property.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top