A consistent naming pattern is one of the most important elements of predictability and discoverability in a managed class library. Widespread use and understanding of these naming guidelines should eliminate many of the most common user questions. This topic provides naming guidelines for the .NET Framework types. For each type, you should also take note of some general rules with respect to capitalization styles, case sensitivity and word choice.
In This Section
Capitalization Styles
- Describes the Pascal case, camel case, and uppercase capitalization styles to use to name identifiers in class libraries.
1Use the following three conventions for capitalizing identifiers.
The first letter in the identifier and the first letter of each subsequent concatenated word are capitalized. You can use Pascal case for identifiers of three or more characters. For example:
BackColor
backColor
UppercaseAll letters in the identifier are capitalized. Use this convention only for identifiers that consist of two or fewer letters. For example:
System.IO System.Web.UI
The following table summarizes the capitalization rules and provides examples for the different types of identifiers.
Identifier Case Example Class Pascal AppDomain Enum type Pascal ErrorLevel Enum values Pascal FatalError Event Pascal ValueChange Exception class Pascal WebException Note Always ends with the suffix Exception.
Read-only Static field Pascal RedValue Interface Pascal IDisposable Note Always begins with the prefix
I
.Method Pascal ToString Namespace Pascal System.Drawing Parameter Camel typeName Property Pascal BackColor Protected instance field Camel redValue Note Rarely used. A property is preferable to using a protected instance field.
Public instance field Pascal RedValue Note Rarely used. A property is preferable to using a public instance field.
Case Sensitivity
- Describes the case sensitivity guidelines to follow when naming identifiers in class libraries.
- To avoid confusion and guarantee cross-language interoperation, follow these rules regarding the use of case sensitivity:
- Do not use names that require case sensitivity. Components must be fully usable from both case-sensitive and case-insensitive languages. Case-insensitive languages cannot distinguish between two names within the same context that differ only by case. Therefore, you must avoid this situation in the components or classes that you create.
- Do not create two namespaces with names that differ only by case. For example, a case insensitive language cannot distinguish between the following two namespace declarations.
namespace ee.cummings; namespace Ee.Cummings;
- Do not create a function with parameter names that differ only by case. The following example is incorrect.
void MyFunction(string a, string A)
- Do not create a namespace with type names that differ only by case. In the following example,
Point p
andPOINT p
are inappropriate type names because they differ only by case.System.Windows.Forms.Point p System.Windows.Forms.POINT p
- Do not create a type with property names that differ only by case. In the following example,
int Color
andint COLOR
are inappropriate property names because they differ only by case.int Color {get, set} int COLOR {get, set}
- Do not create a type with method names that differ only by case. In the following example,
calculate
andCalculate
are inappropriate method names because they differ only by case.void calculate() void Calculate()
Abbreviations
- Describes the guidelines for using abbreviations in type names.
- To avoid confusion and guarantee cross-language interoperation, follow these rules regarding the use of abbreviations:
- Do not use abbreviations or contractions as parts of identifier names. For example, use
GetWindow
instead ofGetWin
. - Do not use acronyms that are not generally accepted in the computing field.
- Where appropriate, use well-known acronyms to replace lengthy phrase names. For example, use
UI
for User Interface andOLAP
for On-line Analytical Processing. - When using acronyms, use Pascal case or camel case for acronyms more than two characters long. For example, use HtmlButton or htmlButton. However, you should capitalize acronyms that consist of only two characters, such as
System.IO
instead ofSystem.Io
. - Do not use abbreviations in identifiers or parameter names. If you must use abbreviations, use camel case for abbreviations that consist of more than two characters, even if this contradicts the standard abbreviation of the word.
- Do not use abbreviations or contractions as parts of identifier names. For example, use
Word Choice
- Lists the keywords to avoid using in type names.
- Avoid using class names that duplicate commonly used .NET Framework namespaces. For example, do not use any of the following names as a class name: System, Collections, Forms, or UI. See the Class Library for a list of .NET Framework namespaces.
In addition, avoid using identifiers that conflict with the following keywords.
AddHandler AddressOf Alias And Ansi As Assembly Auto Base Boolean ByRef Byte ByVal Call Case Catch CBool CByte CChar CDate CDec CDbl Char CInt Class CLng CObj Const CShort CSng CStr CType Date Decimal Declare Default Delegate Dim Do Double Each Else ElseIf End Enum Erase Error Event Exit ExternalSource False Finalize Finally Float For Friend Function Get GetType Goto Handles If Implements Imports In Inherits Integer Interface Is Let Lib Like Long Loop Me Mod Module MustInherit MustOverride MyBase MyClass Namespace New Next Not Nothing NotInheritable NotOverridable Object On Option Optional Or Overloads Overridable Overrides ParamArray Preserve Private Property Protected Public RaiseEvent ReadOnly ReDim Region REM RemoveHandler Resume Return Select Set Shadows Shared Short Single Static Step Stop String Structure Sub SyncLock Then Throw To True Try TypeOf Unicode Until volatile When While With WithEvents WriteOnly Xor eval extends instanceof package var Avoiding Type Name Confusion
- Describes how to avoid using language-specific terminology in order to avoid type name confusion.
- Different programming languages use different terms to identify the fundamental managed types. Class library designers must avoid using language-specific terminology. Follow the rules described in this section to avoid type name confusion.
Use names that describe a type's meaning rather than names that describe the type. In the rare case that a parameter has no semantic meaning beyond its type, use a generic name. For example, a class that supports writing a variety of data types into a stream might have the following methods.
Sub Write(value As Double); Sub Write(value As Single); Sub Write(value As Long); Sub Write(value As Integer); Sub Write(value As Short); [C#] void Write(double value); void Write(float value); void Write(long value); void Write(int value); void Write(short value);
Sub Write(doubleValue As Double); Sub Write(singleValue As Single); Sub Write(longValue As Long); Sub Write(integerValue As Integer); Sub Write(shortValue As Short); [C#] void Write(double doubleValue); void Write(float floatValue); void Write(long longValue); void Write(int intValue); void Write(short shortValue);
C# type name Visual Basic type name JScript type name Visual C++ type name Ilasm.exe representation Universal type name sbyte SByte sByte char int8 SByte byte Byte byte unsigned char unsigned int8 Byte short Short short short int16 Int16 ushort UInt16 ushort unsigned short unsigned int16 UInt16 int Integer int int int32 Int32 uint UInt32 uint unsigned int unsigned int32 UInt32 long Long long __int64 int64 Int64 ulong UInt64 ulong unsigned __int64 unsigned int64 UInt64 float Single float float float32 Single double Double double double float64 Double bool Boolean boolean bool bool Boolean char Char char wchar_t char Char string String string String string String object Object object Object object Object
ReadDouble()As Double ReadSingle()As Single ReadInt64()As Long ReadInt32()As Integer ReadInt16()As Short [C#] double ReadDouble(); float ReadSingle(); long ReadInt64(); int ReadInt32(); short ReadInt16();
ReadDouble()As Double ReadSingle()As Single ReadLong()As Long ReadInteger()As Integer ReadShort()As Short [C#] double ReadDouble(); float ReadFloat(); long ReadLong(); int ReadInt(); short ReadShort();
Namespace Naming Guidelines
- Describes the guidelines to follow when naming namespaces.
- The general rule for naming namespaces is to use the company name followed by the technology name and optionally the feature and design as follows.
CompanyName.TechnologyName[.Feature][.Design]
Microsoft.Media Microsoft.Media.Design
Microsoft.Office
is an appropriate prefix for the Office Automation Classes provided by Microsoft.
Use a stable, recognized technology name at the second level of a hierarchical name. Use organizational hierarchies as the basis for namespace hierarchies. Name a namespace that contains types that provide design-time functionality for a base namespace with the.Design
suffix. For example, the System.Windows.Forms.Design Namespace contains designers and related classes used to design System.Windows.Forms based applications.
A nested namespace should have a dependency on types in the containing namespace. For example, the classes in theSystem.Web.UI.Design depend on the classes in System.Web.UI. However, the classes in System.Web.UI do not depend on the classes in System.Web.UI.Design.
You should use Pascal case for namespaces, and separate logical components with periods, as inMicrosoft.Office.PowerPoint
. If your brand employs nontraditional casing, follow the casing defined by your brand, even if it deviates from the prescribed Pascal case. For example, the namespacesNeXT.WebObjects
andee.cummings
illustrate appropriate deviations from the Pascal case rule.
Use plural namespace names if it is semantically appropriate. For example, useSystem.Collections
rather thanSystem.Collection
. Exceptions to this rule are brand names and abbreviations. For example, useSystem.IO
rather thanSystem.IOs
.
Do not use the same name for a namespace and a class. For example, do not provide both aDebug
namespace and aDebug
class.
Finally, note that a namespace name does not have to parallel an assembly name. For example, if you name an assemblyMyCompany.MyTechnology.dll
, it does not have to contain aMyCompany.MyTechnology
namespace. Class Naming Guidelines
- Describes the guidelines to follow when naming classes.
- The following rules outline the guidelines for naming classes:
- Use a noun or noun phrase to name a class.
- Use Pascal case.
- Use abbreviations sparingly.
- Do not use a type prefix, such as
C
for class, on a class name. For example, use the class nameFileStream
rather thanCFileStream
. - Do not use the underscore character (_).
- Occasionally, it is necessary to provide a class name that begins with the letter I, even though the class is not an interface. This is appropriate as long as I is the first letter of an entire word that is a part of the class name. For example, the class name
IdentityStore
is appropriate. - Where appropriate, use a compound word to name a derived class. The second part of the derived class's name should be the name of the base class. For example,
ApplicationException
is an appropriate name for a class derived from a class namedException
, becauseApplicationException
is a kind ofException
. Use reasonable judgment in applying this rule. For example,Button
is an appropriate name for a class derived fromControl
. Although a button is a kind of control, makingControl
a part of the class name would lengthen the name unnecessarily.
Public Class FileStream Public Class Button Public Class String [C#] public class FileStream public class Button public class String
Interface Naming Guidelines
- Describes the guidelines to follow when naming interfaces.
- The following rules outline the naming guidelines for interfaces:
- Name interfaces with nouns or noun phrases, or adjectives that describe behavior. For example, the interface name IComponent uses a descriptive noun. The interface name ICustomAttributeProvider uses a noun phrase. The name IPersistable uses an adjective.
- Use Pascal case.
- Use abbreviations sparingly.
- Prefix interface names with the letter
I
, to indicate that the type is an interface. - Use similar names when you define a class/interface pair where the class is a standard implementation of the interface. The names should differ only by the letter
I
prefix on the interface name. - Do not use the underscore character (_).
Public Interface IServiceProvider Public Interface IFormatable [C#] public interface IServiceProvider public interface IFormatable
Public Interface IComponent ' Implementation code goes here. End Interface Public Class Component Implements IComponent ' Implementation code goes here. End Class [C#] public interface IComponent { // Implementation code goes here. } public class Component: IComponent { // Implementation code goes here. }
Attribute Naming Guidelines
- Describes the correct way to name an attribute using the Attribute suffix.
- You should always add the suffix
Attribute
to custom attribute classes. The following is an example of a correctly named attribute class.
Public Class ObsoleteAttribute [C#] public class ObsoleteAttribute{}
Enumeration Type Naming Guidelines
- Describes the guidelines to follow when naming enumerations.
- The enumeration (Enum) value type inherits from the Enum Class. The following rules outline the naming guidelines for enumerations:
- Use Pascal case for Enum types and value names.
- Use abbreviations sparingly.
- Do not use an
Enum
suffix on Enum type names. - Use a singular name for most Enum types, but use a plural name for Enum types that are bit fields.
- Always add the FlagsAttribute to a bit field Enum type.
Static Field Naming Guidelines
- Describes the guidelines to follow when naming static fields.
- The following rules outline the naming guidelines for static fields:
- Use nouns, noun phrases, or abbreviations of nouns to name static fields.
- Use Pascal case.
- Do not use a Hungarian notation prefix on static field names.
- It is recommended that you use static properties instead of public static fields whenever possible.
Parameter Naming Guidelines
- Describes the guidelines to follow when naming parameters.
- It is important to carefully follow these parameter naming guidelines because visual design tools that provide context sensitive help and class browsing functionality display method parameter names to users in the designer. The following rules outline the naming guidelines for parameters:
- Use camel case for parameter names.
- Use descriptive parameter names. Parameter names should be descriptive enough that the name of the parameter and its type can be used to determine its meaning in most scenarios. For example, visual design tools that provide context sensitive help display method parameters to the developer as they type. The parameter names should be descriptive enough in this scenario to allow the developer to supply the correct parameters.
- Use names that describe a parameter's meaning rather than names that describe a parameter's type. Development tools should provide meaningful information about a parameter's type. Therefore, a parameter's name can be put to better use by describing meaning. Use type-based parameter names sparingly and only where it is appropriate.
- Do not use reserved parameters. Reserved parameters are private parameters that might be exposed in a future version if they are needed. Instead, if more data is needed in a future version of your class library, add a new overload for a method.
- Do not prefix parameter names with Hungarian type notation.
GetType(typeName As String)As Type Format(format As String, args() As object)As String [C#] Type GetType(string typeName) string Format(string format, object[] args)
Method Naming Guidelines
- Describes the guidelines to follow when naming methods.
- The following rules outline the naming guidelines for methods:
- Use verbs or verb phrases to name methods.
- Use Pascal case.
RemoveAll() GetCharArray() Invoke()
Property Naming Guidelines
- Describes the guidelines to follow when naming properties.
- The following rules outline the naming guidelines for properties:
- Use a noun or noun phrase to name properties.
- Use Pascal case.
- Do not use Hungarian notation.
- Consider creating a property with the same name as its underlying type. For example, if you declare a property named Color, the type of the property should likewise be Color. See the example later in this topic.
Public Class SampleClass Public Property BackColor As Color ' Code for Get and Set accessors goes here. End Property End Class [C#] public class SampleClass { public Color BackColor { // Code for Get and Set accessors goes here. } }
Public Enum Color ' Insert code for Enum here. End Enum Public Class Control Public Property Color As Color Get ' Insert code here. End Get Set ' Insert code here. End Set End Property End Class [C#] public enum Color { // Insert code for Enum here. } public class Control { public Color Color { get {// Insert code here.} set {// Insert code here.} } }
Public Enum Color ' Insert code for Enum here. End Enum Public Class Control Public Property Color As Integer Get ' Insert code here. End Get Set ' Insert code here. End Set End Property End Class [C#] public enum Color {// Insert code for Enum here.} public class Control { public int Color { get {// Insert code here.} set {// Insert code here.} } }
Color.Xxx
will be interpreted as accessing a member that first gets the value of the Color property (type Integer in Visual Basic or typeint in C#) and then accesses a member of that value (which would have to be an instance member of System.Int32).
Event Naming Guidelines
- Describes the guidelines to follow when naming events.
- The following rules outline the naming guidelines for events:
- Use Pascal case.
- Do not use Hungarian notation.
- Use an
EventHandler
suffix on event handler names. - Specify two parameters named sender and e. The sender parameter represents the object that raised the event. The sender parameter is always of type object, even if it is possible to use a more specific type. The state associated with the event is encapsulated in an instance of an event class named e. Use an appropriate and specific event class for the e parameter type.
- Name an event argument class with the
EventArgs
suffix. - Consider naming events with a verb. For example, correctly named event names include Clicked, Painting, andDroppedDown.
- Use a gerund (the "ing" form of a verb) to create an event name that expresses the concept of pre-event, and a past-tense verb to represent post-event. For example, a Close event that can be canceled should have a
Closing
event and aClosed
event. Do not use theBeforeXxx
/AfterXxx
naming pattern. - Do not use a prefix or suffix on the event declaration on the type. For example, use
Close
instead ofOnClose
. - In general, you should provide a protected method called OnXxx on types with events that can be overridden in a derived class. This method should only have the event parameter e, because the sender is always the instance of the type.
Public Delegate Sub MouseEventHandler(sender As Object, e As MouseEventArgs) [C#] public delegate void MouseEventHandler(object sender, MouseEventArgs e);
Public Class MouseEventArgs Inherits EventArgs Dim x As Integer Dim y As Integer Public Sub New MouseEventArgs(x As Integer, y As Integer) me.x = x me.y = y End Sub Public Property X As Integer Get Return x End Get End Property Public Property Y As Integer Get Return y End Get End Property End Class [C#] public class MouseEventArgs : EventArgs { int x; int y; public MouseEventArgs(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } } public int Y { get { return y; } } }
No comments:
Post a Comment