To make code more self-documenting (always an important goal) and to reduce the chance of programming errors, you need an easy way to determine the exact data type of a variable or the exact type of a referenced control in C# code.
Variable naming conventions have long been a hot topic. With the release of .NET, Microsoft has officially recommended that you not use naming conventions (although it's hard to imagine why). As a professional developer, I find this idea counterproductive, and most other developers I have spoken with have no plans to abandon using naming conventions. Because I so firmly believe in them and because they aid the learning process, I have used them, and I teach them in this book. Please be aware that if you don't like naming conventions, you don't have to use them. However, I strongly recommend that you do use naming conventions; the benefits they provide are considerable.
Using Prefixes to Denote Data Type
Table 12.3lists the prefixes of the common data types.
Table 12.3. Prefixes for Common Data Types
Data Type
Prefix
Value
Boolean
bln
blnLoggedIn
Byte
byt
bytAge
Char
chr
chrQuantity
Decimal
dec
decSalary
Double
dbl
dblCalculatedResult
Integer
int
intLoopCounter
Long
lng
lngCustomerID
Object
obj
objWord
Short
sho
shoTotalParts
String
str
strFirstName
The prefix of obj should be reserved for when a specific prefix isn't available. The most common use of this prefix is when referencing Automation libraries of COM applications. For instance, when automating Microsoft Word, you create an instance of Word's Application object. Because no prefix exists specifically for Word objects, obj works just fine (that is, Word.Application objWord = new Word.Application);.
Denoting Scope Using Variable Prefixes
Prefixes are useful not only to denote data types, they also can be used to denote scope (see Table 12.4). In particularly large applications, a scope designator is almost a necessity. Again, C# doesn't care whether you use prefixes, but consistently using prefixes benefits you as well as others who have to review your code.
Table 12.4. Prefixes for Variable Scope
Prefix
Description
Example
g
Global
g_strSavePath
m
Private to class
m_blnDataChanged
(no prefix)
Nonstatic variable, local to method
Other Prefixes
Prefixes aren't just for variables. All standard objects (including forms and controls) can use a three-character prefix. There are simply too many controls and objects to list all the prefixes here, although you will find that I use control prefixes throughout this book.