Practical DiskDiff in C#: C# Style

Most languages develop an expected idiom for expression. When dealing with C character strings, for example, the usual idiom involves pointer arithmetic rather than array references. C# hasn’t been around long enough for programmers to have lots of experience in this area, but the .NET CLR has some guidelines you should consider.

The “Class Library Design Guidelines” section in the .NET documentation details these guidelines, which are especially important for framework or library authors.

The examples in this book conform to the guidelines, so they should be fairly familiar already. The .NET CLR classes and samples also have many examples.

1. Naming

You can use two naming conventions:

  • PascalCasing capitalizes the first character of each word.
  • camelCasing is the same as PascalCasing, except the first character of the first word isn’t capitalized.

In general, use PascalCasing for anything that’s visible externally from a class, such as classes, enums, methods, and so on. The exception to this is method parameters, which you define using camelCasing.

You define private members of classes, such as fields, using camelCasing.

A few other conventions exist in naming:

  • Avoid common keywords in naming to decrease the chance of collisions in other languages.
  • End event classes with EventArgs.
  • End exception classes with Exception.
  • Start interfaces with I.
  • End attribute classes in Attribute.

Hungarian naming (prefixing the name of the variable with the type of the variable) is discouraged for C# code because the added information about the variable isn’t as important as making the code easier to read. For example, strEmployeeName is tougher to read than employeeName, and pointer use is rare in C#.

Conventions such as adding m_ or _ at the beginning of fields to denote that the field belongs to an instance is a matter of personal taste, though the usual convention in sample code is to use simple names without prefixes for fields.

2. Encapsulation

In general, you should heavily encapsulate classes. In other words, a class should expose as little of its internal architecture as possible.

In practice, this means using properties rather than fields to allow for future changes.

Source: Gunnerson Eric, Wienholt Nick (2005), A Programmer’s Introduction to C# 2.0, Apress; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *