Skip to main content

C#: Naming Conventions and coding standards for .NET

So in my first post of year 2013 I'll write about naming conventions and coding standards for .NET.

Naming convention: In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types and functions etc. in source code and documentation.
Reasons for using a naming convention include the following:
·         To reduce the effort needed to read and understand source code
·         To enhance source code appearance (for example, by disallowing overly long names or unclear abbreviations).

Potential benefits: Some of the potential benefits that can be obtained by adopting a naming convention include the following:
·         To provide better understanding in case of code reuse after a long interval of time.
·         to provide meaningful data to be used in project handovers which require submission of program source code and all relevant documentation
·         to provide additional information (i.e., metadata) about the use to which an identifier is put;
·         to enable the use of automated refactoring or search and replace tools with minimal potential for error;
·         To enhance clarity in cases of potential ambiguity.
·         To help avoid "naming collisions" that might occur when the work product of different organizations is combined.

Terminology and Definitions for Naming Conventions:
Pascal Case: 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. Example: Utility, GetValue
Camel Case: The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized. Example: firstName, lastName
Hungarian Notation: A naming convention introduced in the 70s by Microsoft Architect Charles Simonyi. This method involved prefixing variable names with its type (i.e. strName, iCount), and at the time this presented several advantages. Modern programming languages introduced classes and some object-oriented concepts. In a modern IDE, these types of prefixes have almost no value. This naming convention is no longer recommended in Microsoft’s latest naming guidelines. Example: strFirstName, iCounter etc.

So here is table of naming conventions based on above terminologies:
Identifier
Casing Style to use
Example
File name
Pascal casing
ProductCategory
Local variable declarations
Camel casing
firstName
Private variables
Camel casing
studentName
Property declaration
Pascal casing
String Status { getset; }
Public variables
Pascal casing
ForeColor
Const or Static fields
Pascal casing
const String Message = "Hello!!";
Readonly fields
Camel casing
private readonly String _tempValue = "Temp"*Use ‘_’  in front of readonly variable.

Enum
Pascal casing
private class Currency
Namespace
Pascal casing
TestApplication. CurrencyFinder
Class Name or Struct
Pascal casing
private class CurrencyFinder
private struct UserSettings
Interface
Pascal casing
interface ICurrencyConvertor, *Use   “I” in front of interface name to avoid confusion between other class, while inheriting.
Events
Pascal casing
SubmitButtonClick, use “Functionality name” + “Event name”
Method Name
Pascal casing
WriteCurrency()
Delegate
Pascal casing
TestDelegate
 Naming Convention Table for coding

Here I am writing some important points related to naming convention and coding standards with examples:
·         A method should do only “one job”. Do not combine multiple jobs in one method even if those jobs have very few lines of code.
·         Do not include the parent class name within a property name, for example use Employee.Name instead of Employee.EmployeeName
·         Use base and this only in constructors or within an override.
·         Use validation to avoid exceptions and only catch what you can handle.
·         Always place curly braces ({ and }) on a new line.
·         Provide adequate comments.
·         Segregate relevant coding using #region.
·         Group internal class implementation by type in the following order:
a.    Member variables.
b.    Constructors & Finalizers.
c.    Nested Enums, Structs, and Classes.
d.   Properties
e.    Methods
·         Sequence declarations within type groups based upon access modifier and visibility:
a.    Public
b.    Protected
c.    Internal
d.   Private
·         Use PascalCase for Classes, Methods, Public Properties, Enums, and Interfaces
     Reason: It’s easy to tell that PascalCase things are classes or methods. These things have a larger scope and are often consumed by other assemblies or services. 
o   Prefix interfaces with the character "I"
o   Use Pascal case for Constants.

  Example:        
   public class CurrencyFinder // class name
   {
       public Currency CurrentCurrency { getset; }  // public property
       public const string RupeeMessage = "Hey your currency is Rupee"// const     variable
       private void WriteCurrency() // method name
       {
           if (CurrentCurrency == Currency.Rupee)
                 Console.WriteLine(RupeeMessage);
       }
   }
   public enum Currency // enum
   {
       Dollar,
       Rupee,
       Euro,
       Pound
   }
   interface ICurrencyConvertor // interface
   {
       public void ConvertCurrency();
   }

·         Use camelCase for Local Variables, Method Arguments, and Private Member Variables
Reason: Items in this casing are temporary things like a local variable or method argument.  With one exception (member variables), you know the scope is limited to the method so you don’t have worry about breaking anything else. Member variables may be shared with other methods so they are prefixed with “_” to encourage you to pay special attention to it. 
o   Prefix Protected and Private Member Variables with an underscore

  Example:
private string _rupeeMessage = "currency"// private member variable
void WriteCurrency(Currency currency) // method argument
{
    var temp = "hello"// local variable
    if (currency == Currency.Rupee)
        _rupeeMessage = "Hey your currency is Rupee";
}

·         Do not use Hungarian notation or any other type identification in identifiers. For example:
//Correct
int count;
string name;
// Avoid
int iCount;
string strName;

·         Do not use Screaming Caps for constants or readonly variables
//Correct
public const string Message = "Hello!!";
//Avoid
public const string MESSAGE = "Hello!!";
  
·         Do not use Underscores in identifiers, though you can prefix private readonly variables with an underscore.
//Correct
public String firstName;
//Avoid
public String first_Name;

·         Avoid using abbreviations unless the full name is excessive.
//Correct
CurrencyFinder currencyFinder;
//Avoid
CurrencyFinder curFindr;

·         Use implicit type var for local variable declarations. For example:
Var currencyFinder = new CurrencyFinder();
Var message = "Hello!!";

·         Try to prefix Boolean variables with “Can”, “Is” or “Has”
bool isMember = false;
bool hasAccess = false;

·         File name should match with name of main class. Exception: file names with partial classes reflect their source or purpose, e.g. designer, generated, etc.
//Located in Currency.cs
public partial class Currency
{
    //...
}
//Located in Currency.generated.cs
public partial class Currency
{
    //...
}

·         Use meaningful, descriptive words for naming variables. Some tips to choose method, class and variable names.
o   Use normal prose. For example FirstName is better than NameFirst 
o   Use singular nouns for classes and variables. UserCollection is better than Users.
o   Function name should tell you what it does
o   Use verbs in function names to help your code “read” better.  GetUserList() is better than UserList().
o   Don’t use generic words like do, manage, resolve, handle, etc. SendMail is better than ManageMail, DoMail, etc.
o   Avoid naming conflicts with existing .NET Framework namespaces or types.
o   Avoid using variable names that resemble keywords.  Page, List, Klass etc.
·         Guidelines for Namespaces and Assembly:
o   Use appropriate namespace to avoid name conflicts.
o   Do choose names that indicate groups of related functionality.
o   Do not use the same name for a namespace and a type in that namespace. For example, do not use TestUser for a namespace name and also provide a class named TestUser in the same namespace. 
o   Consider using plural names where appropriate. For example, System.Collections instead of System.Collection
o   Assembly names should be used to group related classes. Often these are consumed by clients or other teams, so it’s especially important to do a good job. If someone saw it for the first time, is it reasonable that person will understand its purpose?
o   Place namespace “using” statements together at the top of file. Group .NET namespaces above custom namespaces.

·         Variables & Types
o   Use built-in C# native data types vs. .NET CTS types. For example use int NOT Int32.
o   Only declare member variables as private. Use properties to provide access to them with public, protected, or internal access modifiers.
o   Try to use int for any non-fractional numeric values that will fit the int datatype - even variables for nonnegative numbers.
o   Only use long for variables potentially containing values too large for an int.
o   Try to use double for fractional numbers to ensure decimal precision in calculations.
o   Only use float for fractional numbers that will not fit double or decimal.
o   Try to use decimal when fractional numbers must be rounded to a fixed precision for calculations. Typically this will involve money
o   Only declare constants for simple types. And declare readonly or static readonly variables instead of constants for complex types.
o   Always prefer C# Generic collection types over standard or strong-typed collections.
o   Try to use the “@” prefix for string literals instead of escaped strings.
o   Prefer String.Format() or StringBuilder over string concatenation.
o   Never concatenate strings inside a loop.
·         Avoid creating recursive methods. Use loops or nested loops instead.
·         Use the ternary conditional operator only for trivial conditions. Avoid complex or compound ternary operations. For example:
   var result = isValid ? 9 : 4;

·         Avoid evaluating Boolean conditions against true or false. For example:
   // Bad!
   if (isValid == true)
   {
        //
   }
   // Good!
   if (isValid)
   {
        //
   }


·         Wrap instantiation of IDisposable objects with a “using” statement to ensure that Dispose() is automatically called. For example:
   using (SqlConnection cn = new SqlConnection(_connectionString))
   {
   }

Always write clean and clear code!!!

Popular posts from this blog

C#: Merging Excel cells with NPOI HSSFWorkbook

In this post we’ll see how to merge the two or more cell with each other while creating the excel sheet using NPOI.
Mentioned below is code to merge multiple cells, in this example we are merging first cell to fifth cell of first row (you can adjust row or cell range by passing particular parameters in CellRangeAddress).
//Created new Workbook var hwb = new NPOI.HSSF.UserModel.HSSFWorkbook(); //Create worksheet with name. var sheet = hwb.CreateSheet("new sheet"); //Create row and cell. var row = sheet.CreateRow(0); var cell = row.CreateCell(0); ; //Set text inside cell cell.SetCellValue("This is Merged cell"); cell.CellStyle.WrapText = true; //define cell range address // parameters: -> first row to last and first cell to last cell var cra = new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 4); //Add merged region to sheet. sheet.AddMergedRegion(cra);
Hope this solution helps you J

Calculate Sum and average of two or more Textbox values using JQuery

We can calculate sum and average of values entered in textboxes with the help of small piece of jQuery code.
First of all let’s create a HTML form where we’ll ask user to enter marks in each subject, under body section add following HTML:
<tableclass="demo-table"> <trclass="label"> <tdcolspan="2">Please enter marks(0-99):</td> </tr> <tr> <td>English</td> <td> <inputtype="text"class="txtMarks"name="txtMarks"

Difference between Web API, WCF and Web Service

So now we have got the basic idea about Web API, now let’s do some comparison of Web API with WCF and web services.
Web Service WCF Web API Web services created as file with .asmx extension. WCF create with .svc extension Web API are simple class file with .cs(for C#) extension. Web API is inherited from “ApiController” and class name must end with “Controller”. It is SOAP based service and return data in XML form. It is also based on SOAP and return data in XML form. Web API is HTTP based service and by default it return data in JSON or XML form. It supports only HTTP protocol. It supports various protocols like TCP, HTTP, HTTPS, Named Pipes, and MSMQ. It supports HTTP protocol. It can be hosted only on IIS. It can be hosted with in the application or on IIS or using window service. It can be hosted with in the application or on IIS. It is not open source but can be consumed by any client that understands xml. It is not open source but can be consumed by any client t…