Prev | Current Page 237 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

For now, I??™ll talk about an ???instance with a value??? and an ???instance
without a value,??? which mean instances where the HasValue property returns true or
false, respectively.
Now that we know what we want the properties to achieve, let??™s see how to create
an instance of the type. Nullable has two constructors: the default one (creating
an instance without a value) and one taking an instance of T as the value. Once an
instance has been constructed, it is immutable.
NOTE Value types and mutability??”A type is said to be immutable if it is designed so
that an instance can??™t be changed after it??™s been constructed. Immutable
types often make life easier when it comes to topics such as multithreading,
where it helps to know that nobody can be changing values in one
thread while you??™re reading them in a different one. However, immutability
is also important for value types. As a general rule, value types should
almost always be immutable. If you need a way of basing one value on
another, follow the lead of DateTime and TimeSpan??”provide methods
that return a new value rather than modifying an existing one. That way,
you avoid situations where you think you??™re changing a variable but actually
you??™re changing the value returned by a property or method, which is just
a copy of the variable??™s value. The compiler is usually smart enough to
warn you about this, but it??™s worth trying to avoid the situation in the first
place.


Pages:
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249