My blog has moved!

You should be automatically redirected in 6 seconds. If not, visit
http://www.csharpblog.net/
and update your bookmarks.

Monday 19 November 2007

Coding Tip 2 - Fields Change

Tip 2 – Non-constant fields should NOT be visible

Static fields that are neither constants nor read-only are not thread-safe. Access to such a field must be carefully controlled and requires advanced programming techniques for synchronizing access to the class object. Because these are difficult skills to learn and master, and testing such an object poses its own challenges, static fields are best used to store data that does not change. This rule applies to libraries; applications should not expose any fields.
Example:

WRONG:
public static DateTime publicField = DateTime.Now;
//This is wrong because the field is public and not a literal

CORRECT:
public static readonly DateTime literalField = DateTime.Now;
//Correct because it is a literal read-only field
static DateTime privateField = DateTime.Now;
//Correct because it is a private field.

1 comment:

gucci said...
This comment has been removed by a blog administrator.