none
msdn C# coding standards

    Question

  • Guys!

    I follow msdn C# coding standards: Design Guidelines for Class Library Developers (http://msdn.microsoft.com/en-us/library/czefa0ke.aspx) so that it is easy to use (copy and paste) msdn code in the program.

    However, I come across a lot of discrepancies as far as msdn code's coding standards are concerned. For instance, according to .NET Framework General Reference Capitalization Styles (http://msdn.microsoft.com/en-us/library/x2dbyw72(VS.71).aspx):

    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

     

    And according to .NET Framework Developer's Guide - ADO.NET Code Examples - ADO.NET Data Provider Examples – (http://msdn.microsoft.com/en-us/library/dw70f090.aspx#_SqlClient)

    Visual Basic

    Option Explicit On
    Option Strict On
     
    Imports System
    Imports System.Data
    Imports System.Data.SqlClient
     
    Public Class Program
        Public Shared Sub Main()
     
            Dim connectionString As String = _
                "Data Source=(local);Initial Catalog=Northwind;" _
                & "Integrated Security=true"
     
            ' Provide the query string with a parameter placeholder.
            Dim queryString As String = _
                "SELECT ProductID, UnitPrice, ProductName from dbo.Products " _
                & "WHERE UnitPrice > @pricePoint " _
                & "ORDER BY UnitPrice DESC;"
     
            ' Specify the parameter value.
            Dim paramValue As Integer = 5
     
            ' Create and open the connection in a using block. This
            ' ensures that all resources will be closed and disposed
            ' when the code exits.
            Using connection As New SqlConnection(connectionString)
     
                ' Create the Command and Parameter objects.
                Dim command As New SqlCommand(queryString, connection)
                command.Parameters.AddWithValue("@pricePoint", paramValue)
     
                ' Open the connection in a try/catch block. 
                ' Create and execute the DataReader, writing the result
                ' set to the console window.
                Try
                    connection.Open()
                    Dim dataReader As SqlDataReader = _
                     command.ExecuteReader()
                    Do While dataReader.Read()
                        Console.WriteLine( _
                            vbTab & "{0}" & vbTab & "{1}" & vbTab & "{2}", _
                         dataReader(0), dataReader(1), dataReader(2))
                    Loop
                    dataReader.Close()
     
                Catch ex As Exception
                    Console.WriteLine(ex.Message)
                End Try
                Console.ReadLine()
            End Using
        End Sub
    End Class
     

    C#

    using System;
    using System.Data;
    using System.Data.SqlClient;
     
    class Program
    {
        static void Main()
        {
            string connectionString =
                "Data Source=(local);Initial Catalog=Northwind;"
                + "Integrated Security=true";
     
            // Provide the query string with a parameter placeholder.
            string queryString =
                "SELECT ProductID, UnitPrice, ProductName from dbo.products "
                    + "WHERE UnitPrice > @pricePoint "
                    + "ORDER BY UnitPrice DESC;";
     
            // Specify the parameter value.
            int paramValue = 5;
     
            // Create and open the connection in a using block. This
            // ensures that all resources will be closed and disposed
            // when the code exits.
            using (SqlConnection connection =
                new SqlConnection(connectionString))
            {
                // Create the Command and Parameter objects.
                SqlCommand command = new SqlCommand(queryString, connection);
                command.Parameters.AddWithValue("@pricePoint", paramValue);
     
                // Open the connection in a try/catch block. 
                // Create and execute the DataReader, writing the result
                // set to the console window.
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        Console.WriteLine("\t{0}\t{1}\t{2}",
                            reader[0], reader[1], reader[2]);
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                Console.ReadLine();
            }
        }

     

    The table recommends Camel case only for Parameter and Protected instance field, but Camel case is used for filed name and lowercase if used for instance variables.

    I am a bit confused now. I want to follow msdn guidelines as it is easy to use (copy and paste) msdn code in the program and there’s no license issues.

    Please guide.

    Thanks

    Monday, May 25, 2009 6:02 AM

Answers

  • Hi,

    You might be interested in StyleCop.
    StyleCop analyzes C# source code to enforce a set of style and consistency rules.

    http://code.msdn.microsoft.com/sourceanalysis
    www.dsmyth.net | www.dsmyth.net/wiki
    • Marked as answer by Roahn Luo Tuesday, May 26, 2009 10:29 AM
    Monday, May 25, 2009 8:42 AM
  • The table recommends Camel case only for Parameter and Protected instance field, but Camel case is used for filed name and lowercase if used for instance variables.
    "The table recommends Camel case only for Parameter and Protected instance field " This is not true. The word only you added yourself.
    The MDSN says nothing about the internal(or private) field standards. Probably, because they have no a common convention even inside Microsoft.

    In the most cases the code in MSDN have camel case for internal/private fields. But some times you can see also the usage of the "_" prefix for the field name(or, worst, IMO, the "m" prefix).

    So, the rules for this fields you can use as you wish. But be consequent and constant in the chosen style. Personally I use the following rule:
    as the public property uses PascalCase - ThisIsAnExample, the private use the camelCase - thisIsAnExample.
    private bool is Connected;
    public bool Is Connected
    {
        get{ return this.isConnected; }
        set{ this.isConnected = value; }
    }

    In Visual Studio 2008 you can code analyzer
    (Analyzer menu Item) for perform a syntactic code analyze...

    Best regards, Sergiu
    • Edited by Sergiu Dudnic Monday, May 25, 2009 10:12 AM
    • Marked as answer by Roahn Luo Tuesday, May 26, 2009 10:29 AM
    Monday, May 25, 2009 10:05 AM

All replies

  • Why coding standards?

    A coding standards document tells developers how they must write their code. Instead of each developer coding in their own preferred style, they will write all code to the standards outlined in the document. This makes sure that a large project is coded in a consistent style -- parts are not written differently by different programmers. Not only does this solution make the code easier to understand, it also ensures that any developer who looks at the code will know what to expect throughout the entire application.

    Coding standards are great -- but how do you decide which standards you want to apply, and how they will be defined? When you formulate your ideal coding style, you should think about these points:

    1. Can you actually read the code? Is it spaced out clearly?
      • Do you separate blocks of code into 'paragraphs' so that different sections are easily defined?
      • Are you using indentation to show where control structures (if, else, while and other loops) begin and end, and where the code within them is?
      • Are your variable naming conventions consistent throughout the code and do they briefly describe that data that they'll contain?
      • Are functions named in accordance with what they do?


    2. If you come back to the code in a few weeks or months, will you be able to work out what's happening without needing to look at every line?

    3. How are you commenting the work?

    4. Have you used complex language functions/constructs that are quicker to write but affect readability?

    Once you've considered those points, you can begin to draft your coding standards. Consult with your team members (if any) and compare how they code to your own style -- you shouldn't force total change upon everyone. Compromise and incorporate elements of everyone's style. If someone has been coding in a specific way for a long time, it will take a while for that developer to change to the new method. Developers will likely adopt the style gradually, just as an accent develops over time.

    Source

    So recherche , it upto you to opt for a coding standard and stick with it.

    I know this was not the answer you are looking for. But the devloper who wrote those samples might be following his own teams coding standards.

     

     


    Thanks,
    A.m.a.L
    .Net Goodies
    Remember to click "mark as answered" when you get a correct reply to your question
    Monday, May 25, 2009 7:16 AM
  • Hi,

    You might be interested in StyleCop.
    StyleCop analyzes C# source code to enforce a set of style and consistency rules.

    http://code.msdn.microsoft.com/sourceanalysis
    www.dsmyth.net | www.dsmyth.net/wiki
    • Marked as answer by Roahn Luo Tuesday, May 26, 2009 10:29 AM
    Monday, May 25, 2009 8:42 AM
  • The table recommends Camel case only for Parameter and Protected instance field, but Camel case is used for filed name and lowercase if used for instance variables.
    "The table recommends Camel case only for Parameter and Protected instance field " This is not true. The word only you added yourself.
    The MDSN says nothing about the internal(or private) field standards. Probably, because they have no a common convention even inside Microsoft.

    In the most cases the code in MSDN have camel case for internal/private fields. But some times you can see also the usage of the "_" prefix for the field name(or, worst, IMO, the "m" prefix).

    So, the rules for this fields you can use as you wish. But be consequent and constant in the chosen style. Personally I use the following rule:
    as the public property uses PascalCase - ThisIsAnExample, the private use the camelCase - thisIsAnExample.
    private bool is Connected;
    public bool Is Connected
    {
        get{ return this.isConnected; }
        set{ this.isConnected = value; }
    }

    In Visual Studio 2008 you can code analyzer
    (Analyzer menu Item) for perform a syntactic code analyze...

    Best regards, Sergiu
    • Edited by Sergiu Dudnic Monday, May 25, 2009 10:12 AM
    • Marked as answer by Roahn Luo Tuesday, May 26, 2009 10:29 AM
    Monday, May 25, 2009 10:05 AM