Prev | Current Page 393 | Next

Jon Skeet

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


NOTE Terminology: Automatic property vs. automatically implemented property??”When
automatically implemented properties were first discussed, long before
the full C# 3 specification was published, they were called automatic properties.
Personally, I find this a lot less of a mouthful than the full name, and
it??™s not like anything other than the implementation is going to be automatic.
For the rest of this book I will use automatic property and automatically
implemented property synonymously.
The feature of C# 2 that allows you to specify different access for the getter and the
setter is still available here, and you can also create static automatic properties. You need
to be careful with static properties in terms of multithreading, however??”although most
types don??™t claim to have thread-safe instance members, publicly visible static members
usually should be thread-safe, and the compiler doesn??™t do anything to help you in this
respect. It??™s best to restrict automatic static properties to be private, and make sure you
do any appropriate locking yourself. Listing 8.1 gives an example of this.
public class Person
{
public string Name { get; private set; }
public int Age { get; private set; }
Listing 8.1 A Person class that counts created instances
Declares properties
with public getters
210 CHAPTER 8 Cutting fluff with a smart compiler
private static int InstanceCounter { get; set; }
private static readonly object counterLock = new object();
public Person(string name, int age)
{
Name = name;
Age = age;
lock (counterLock)
{
InstanceCounter++;
}
}
}
An alternative in this case is to use a simple static variable and rely on Interlocked.


Pages:
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405