Top Banner

of 26

C_Sharp Coding Standards and Best Practices-v1.2.pdf

Jun 02, 2018

Download

Documents

surbicain2
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    1/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 1 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    C# Coding Standards andBest Practices

    SiemensAuthor: Fanesi JuanDept.: I MTTel.: +54 291 455 6141Mail: [email protected]

    This documentation is valid since version V01.2

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    2/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 2 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    History

    Revisi on Date Change Sections Responsible

    1.0 2012-08-24 General review Facundo Glaeser

    1.1 2013-10-25 Good Progrmming Practices

    Exception Handling and Logging

    Facundo Glaeser / Edgardo Gonzalez

    1.2 2013-11-22 Exception Handling and Logging(Log4Net examples)

    Facundo Glaeser

    It is not permitted to distribute, copy, use and disclose thecontents of this document without specific permission.

    We have checked the contents of this document for correctnesswith the described hardware and software. Deviations however,cannot be completely avoided. Therefore no guarantee can begiven for the complete correctness of this document.However, the contents of this document are regularly checkedand necessary corrections will be made in later revisions.We are grateful for any suggestions f or improvement.

    Violations will be liable for compensation.

    All rights are reserved, especially for patents or GM entries.

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    3/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 3 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    Intellectual Property Rights and Confidentiality

    This document contains valuable trade secrets and confidential information of Siemens and the content of

    this document is and shall remain our intellectual property right. You shall keep this document and all itscontent strictly confidential, not disclose it or any part thereof to any third party without our prior writtenconsent and not use any information, specification or data contained in this document for other purposesthan for the evaluation of our document.

    No part of this document is allowed to be adapted, copied, reproduced, duplicated, translated into anotherlanguage, distributed or processed (print, photocopy, microfilm or any other process), neither by the use ofelectronic systems nor otherwise without the prior written permission of Siemens.

    You shall limit access to our document and to any part thereof to those of your employees reasonablyrequired being aware thereof and you shall ensure their strict adherence to the provisions of confidentialityand restriction of use as expressed above.

    Any violation of the above provisions will be brought before the competent court in accordance with theapplicable law.

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    4/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 4 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    Table of Contents

    1 INTRODUCTION 5

    2 NAMING CONVENTIONS AND STANDARDS 6

    3 IDENTATION, SPACING AND COMMENTS 9

    4 GOOD PROGRAMMING PRACTICES 13

    5 DATABASE 19

    6 ARCHITECTURE 20

    7 EXCEPTION HANDLING AND LOGGING 21

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    5/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 5 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    1 INTRODUCTION

    This document describes rules and recommendations for developing applications and class libraries usingthe C# Language. The goal is to define guidelines to enforce consistent style and formatting and helpdevelopers avoid common mistakes.

    Anybody can write code. With a few months of programming experience, you can write 'workingapplications'. Making it work is easy, but doing it the right way requires more work, than just making itwork.

    Is not the same write working code that good code. Everyone may have different definitions for the termgood code, but nearly all of them would coincide the following are characteristics of good code:

    Reliable

    Maintainable

    Efficient

    To develop code with these characteristics you must follow coding standards and best practices.

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    6/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 6 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    2 NAMING CONVENTIONS AND STANDARDS

    Use English language for all: methods, classes, properties, comments, variables, etc.

    Note:

    The terms Pascal Casing and Camel Casing are used throughout this document.

    Pascal Casing:First character of all words are Upper Case and other characters are Lower Case.

    Example: BackColor

    Camel Casing:First character of all words, except the first word are Upper Case and other characters areLower Case.

    Example: backColor

    Use Pascal Casing for Class names

    public class HelloWorld{

    ...}

    Use Pascal Casing for Method names

    public void SayHello(string name){

    ...}

    Use Pascal Casing for Properties

    public int Number{

    get; set;}

    Use Camel Casing for Variables and Method parameters

    int totalCount= 0;void SayHello(string name)

    {string fullMessage= "Hello " + name;...

    }

    Use the prefix I with Camel Casing for Interfaces (Example: IEntity)

    Methods with return values should have a name describing the value returned. (Example:GetObjectState())

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    7/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 7 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    Use Meaningful, descriptive words to name variables. Do not use abbreviations.

    Good:

    stringaddressintsalary

    Not Good:stringnamstringaddrintsal

    Avoid using abbreviations unless the full name is excessive. (Example, use OrderManagament.csinstead OM.cs).

    Any abbreviations must be widely known and accepted.

    Do not use single character variable names like i, n, setc. Use names like index, temp

    One exception in this case would be variables used for iterations in loops:for (inti = 0; i < count; i++ ){

    ...}

    If the variable is used only as a counter for iteration and is not used anywhere else in the loop, manypeople still like to use a single char variable (i) instead of inventing a different suitable name.

    Do not use underscore _ for local variable names.

    All member variables must be prefixed with underscore _ so that they can be identified from otherlocal variables

    Prefix booleanvariables, properties and methods with is or similar prefixes.

    private bool_isFinished

    Namespace names should follow the standard pattern:

    ...

    The namespaces neither abbreviations of them should be in the class names or folder names.

    Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables.Here are some examples:

    Control Prefix

    Label lblTextBox txtDataGrid dtgButton btnImageButton imbHyperlink hlk

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    8/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 8 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    DropDownList ddlListBox lstDataList dtl

    Repeater repCheckbox chkCheckBoxList cblRadioButton rdoRadioButtonList rblImage imgPanel pnlPlaceHolder phdTable tbl

    File name should match with class name. For example, for the class HelloWorld, the file name shouldbe HelloWorld.cs

    Use Pascal Case for file names. Keep related Class files in single Class Library.

    Suffix custom exception classes with Exception

    public classLoginFailedException : Exception

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    9/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 9 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    3 IDENTATION, SPACING AND COMMENTS

    Use TAB for indentation. Do not use SPACES. Define the Tab size as 4.

    Comments should be in the same level as the code (use the same level of indentation).

    Good:

    // Format a message and displaystringfullMessage = "Hello " + name;DateTimecurrentTime = DateTime.Now;stringmessage = fullMessage + ", the time is : " + currentTime.ToShortTimeString();MessageBox.Show ( message );

    Not Good:

    // Format a message and displaystringfullMessage = "Hello " + name;DateTimecurrentTime = DateTime.Now;stringmessage = fullMessage + ", the time is : " + currentTime.ToShortTimeString();MessageBox.Show ( message );

    Curly braces {} should be in the same level as the code outside the braces.

    Use one blank line to separate logical groups of code.

    Good:boolSayHello ( stringname ){

    stringfullMessage = "Hello " + name;DateTimecurrentTime = DateTime.Now;

    stringmessage = fullMessage + ", the time is : " + currentTime.ToShortTimeString();

    MessageBox.Show ( message );

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    10/26

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    11/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 11 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    Good and meaningful comments make code more maintainable. However, donot write comments forevery line of code and every variable declared.

    All comments should be written in the same language, be grammatically correct, and containappropriate punctuation.

    Use //or ///for comments. Avoid using /* */

    Write comments wherever required. But good readable code will require very less comments. If allvariables and method names are meaningful, that would make the code very readable and will notneed many comments. Anyway, classes, methods and properties, in general, should have commentsusing Summary.

    /// /// This component manages the relocation (if necessary) of barring tus in bin locations./// publicclassRelocationManager{

    }

    /// /// Gets or sets the data access registry./// /// The data access registry.[RequiredProperty]publicIDataAccessRegistryDataAccessRegistry{

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    12/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 12 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    get;set;

    }

    /// /// Gets the waiting master tord for this tord./// /// The sub tord./// Returns the waiting master tord.publicTordGetWaitingMasterTord(TordsubTord){

    }

    Do not write comments if the code is easily understandable without comment.

    If you have to write some complex logic, document it very well with sufficient comments.

    Fewer lines of comments will make the code more elegant. But if the code is not clean/readable andthere are less comments, that is worse.

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    13/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 13 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    4 GOOD PROGRAMMING PRACTICES

    Avoid writing very long methods. A method should typically have 1~25 lines of code. If a method hasmore than 25 lines of code, you must consider re factoring into separate methods.

    Avoid passing too many parameters to a method. If you have more than 4-5 parameters, it is a goodcandidate to define a class or structure.

    Do not pass null as a parameter. Because there is no good way to deal with null, the better approachis to forbid pasing null by default. This way, you will notice of a problem in case you have a null in anargument.

    Method name should tell what it does. If the method name is obvious, there is no need of

    documentation explaining what the method does:

    Good:

    publicvoidSavePhoneNumber (stringphoneNumber ){

    // Save the phone number.}

    Not Good:

    // This method will save the phone number.publicvoidSaveDetails (stringphoneNumber )

    { // Save the phone number.}

    A method should do only 'one job'. Do not combine more than one job in a single method, even ifthose jobs are very small.

    Good:

    // Save the address.SaveAddress (address);

    // Send an email to the supervisor to inform that the address is updated.SendEmail (address, email);

    publicvoidSaveAddress (stringaddress){

    // Save the address.// ...

    }

    publicvoidSendEmail (stringaddress, stringemail){

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    14/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 14 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    // Send an email to inform the supervisor that the address is changed.// ...

    }

    Not Good:

    // Save address and send an email to the supervisor to inform that// the address is updated.SaveAddress (address, email);

    publicvoidSaveAddress (stringaddress, stringemail){

    // Job 1.// Save the address.// ...

    // Job 2.// Send an email to inform the supervisor that the address is changed.// ...

    }

    Use the C# specific types (aliases), rather than the types defined in System namespace.

    intage; (NOT Int16)stringname; (NOT String)objectcontactInfo; (NOT Object)

    Do not hardcode numbers. Use constants instead. Declare constant in the top of the file and use it inyour code.

    However, using constants are also not recommended. You should use the constants in the config fileor database so that you can change it later. Declare them as constants only if you are sure this valuewill never need to be changed.

    Do not hardcode strings. Use resource files.

    Convert strings to lowercase or upper case before comparing. This will ensure the string will matcheven if the string being compared has a different case.

    if(name.ToLower() == john){

    //}

    Use String.Empty instead of

    Good:

    If(name == string.Empty)

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    15/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 15 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    {// do something

    }

    Not Good:

    If( name == ){

    // do something}

    Use enum wherever required. Do not use numbers or strings to indicate discrete values.

    Good:

    enumMailTypes

    {Html,PlainText,Attachment

    }

    voidSendMail (stringmessage, MailTypesmailType){

    switch( mailType ){

    caseMailTypes.Html:// Do something

    break;caseMailTypes.PlainText:

    // Do somethingbreak;

    caseMailTypes.Attachment:// Do somethingbreak;

    default:// Do somethingbreak;

    }}

    Not Good:

    voidSendMail (stringmessage, stringmailType){

    switch( mailType ){

    case"Html":// Do somethingbreak;

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    16/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 16 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    case"PlainText":// Do somethingbreak;

    case"Attachment":// Do somethingbreak;

    default:// Do somethingbreak;

    }}

    Do not make the member variables public or protected. Keep them private and exposepublic/protected Properties.

    Never hardcode a path or drive name in code. Get the application path programmatically and userelative path.

    Error messages should help the user to solve the problem. Never give error messages like "Error inApplication", "There is an error" etc. Instead give specific messages like "Failed to update database.Please make sure the login id and password are correct."

    Show short and friendly message to the user. But log the actual error with all possible information. Thiswill help a lot in diagnosing problems.

    Do not have more than one class in a single file.

    Avoid having very large files. If a single file has more than 1000 lines of code, it is a good candidate forrefactoring. Split them logically into two or more classes. Also, if the logic of the class is stronglyrelated you can divide it in several partial Classes.

    Avoid public methods and properties, unless they really need to be accessed from outside the class.Use internalif they are accessed only within the same assembly.

    If you are opening database connections, sockets, file stream etc, always close them in the finallyblock. This will ensure that even if an exception occurs after opening the connection, it will be safelyclosed in the finallyblock.

    Avoid ToString() and use Convert.ToString() Method

    Before using any instance method/properties always check that object is not null.

    If(employee != null){

    stringname = employee.Name;

    }

    Avoid Explicit casting. Use the as operator to defensively cast to a type.

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    17/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 17 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    Good:

    objectmyObject = newEmployee();

    //the following sentence returns NULL because myObject is not stringstringcastedValue = myObject as string;

    Not Good:

    objectmyObject = newEmployee();//the following sentence throws InvalidCastException because myObject is not stringstringcastedValue = (string) myObject;

    Avoid function calls in Boolean conditions statements. Assign into local variables and check on them

    boolIsEverythingOk(){

    }

    Good:

    boolok = IsEverythingOk();If(ok){

    }

    Not Good:

    If(IsEverythingOk()){

    }

    Avoid explicit properties that do nothing except access a member variable. Use automatic propertiesinstead

    Good:

    publicintNumber{

    get; set;

    }Not Good:

    privateint_number;publicintNumber{

    get{

    return_number;}

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    18/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 18 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    set{

    _number = value;

    }}

    Use Powerful, configurable and flexible Logging class heavily!. For example: Log4Net.

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    19/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 19 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    5 DATABASE

    Never hard-code connection string. Always declare connection string in configuration file(app.config/web.config]) and use it from there only.

    Always use Stored procedures and avoid using SQL Statements in the code. SQL Statements eatsyour network bandwidth.

    Batch operation should be atomic. So, always use Transaction for this type of operations. (If eithertask fails, the both operations should be rolled back)

    Dont put complex business logic inside the stored procedure. It should go under Business LogicLayer.

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    20/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 20 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    6 ARCHITECTURE

    Always use multi layer (N-Tier) architecture.

    Never access database from the UI pages. Always have a data layer class which performs all thedatabase related tasks. This will help you support or migrate to another database back end easily.

    Use try-catchin your data layer to catch all database exceptions. This exception handler should recordall exceptions from the database. The details recorded should include the name of the command beingexecuted, stored procedure name, parameters, connection string used, etc. After recording theexception, it could be re thrown so that another layer in the application can catch it and takeappropriate action.

    Separate your application into multiple assemblies. Group all independent utility classes into aseparate class library. All your database related files can be in another class library

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    21/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 21 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    7 EXCEPTION HANDLING AND LOGGING

    Never do a 'catch exception and do nothing'. If you hide an exception, you will never know if the

    exception happened or not. You should always try to avoid exceptions by checking all the errorconditions programmatically. In any case, catching an exception and doing nothing is not allowed. Inthe worst case, you should logthe exception and proceed.

    In case of exceptions, give a friendly message to the user, but logthe actual error with all possibledetails about the error, including the time it occurred, method, class name, etc.

    Always catch exceptions from specific to generic.

    public classTryCatchDemo{

    staticvoidMain(string[] args){

    try{

    File.OpenRead("NonExistentFile");}catch(ArgumentExceptione1){

    log.Error(, e1);

    }catch(FileNotFoundExceptione2){

    log.Error(, e2);

    }catch(UnauthorizedAccessExceptione3){

    log.Error(, e3);

    }catch(Exceptione4){

    log.Error(, e4);

    }

    }}

    Always logthe exceptions and critical business operations (Database, any other data source, etc).

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    22/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 22 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    Do not return null. If you need to retrieve a collection or List it is better to return an empty collection orList. This way, the null check is not necessary. To think in code with null checks could have badresults if you forget one of them. As a result, you will have no null checks and a higher performance

    code.

    Good:publicList GetEquipments(){

    if (ThereAreEquipments()){

    //return the Equipment data}else{

    return new List();

    }}

    List equipmentList = GetEquipments();

    foreach (Equipment equipment in equipmentList){

    stringequipmentName = equipment.Name;..

    }

    Not Good:

    publicList GetEquipments(){

    List result = null;

    if (ThereAreEquipments()){

    result new List();}

    return result;}

    List equipmentList = GetEquipments();

    if (equipmentList != null){

    foreach (Equipment equipment in equipmentList){

    stringequipmentName = equipment.Name;}

    }

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    23/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 23 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    If you need to return a specific object and it is not found, consider throwing an exception. It is better thanreturn a null and then make the null check. As a result, the chance of NullReferenceException will beminimized and the code will be cleaner.

    Good:public MaterialLotGetMaterialLot(stringlotId){

    if (MaterialLotExist()){

    return lotList.Single(m => m.Id == lotId);

    }else{

    throw new Exception(Can not find the Material Lot + lotId);}

    }

    try{

    MaterialLotlot = GetMaterialLot(lotId);

    }catch(Exceptione){

    log.WarnFormat(, e);throw;

    }

    Not Good:

    public MaterialLotGetMaterialLot(stringlotId){

    MaterialLot resultLot = null;

    if (MaterialLotExist()){

    return lotList.Single(m => m.Id == lotId);

    }

    return resultLot;

    }

    MaterialLotlot = GetMaterialLot(lotId);

    if (lot != null){

    MaterialLotlot = GetMaterialLot(lotId);

    string lotName = lot.Name;}

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    24/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 24 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    When you re throw an exception, use the throwstatement without specifying the original exception.This way, the original call stack is preserved:

    Good:catch{

    // do whatever you want to handle the exceptionthrow;

    }

    Not Good:

    catch (Exceptionex){

    // do whatever you want to handle the exceptionthrow ex;

    }

    Do not write try-catch in all your methods. Use it only if there is a possibility that a specific exceptionmay occur and it cannot be prevented by any other means. For example, if you want to insert a recordif it does not already exists in database, you should try to select record using the key. Somedevelopers try to insert a record without checking if it already exists. If an exception occurs, they willassume that the record already exists. This is strictly not allowed. You should always explicitly checkfor errors rather than waiting for exceptions to occur. On the other hand, you should always useexception handlers while you communicate with external systems like network, hardware devices etc.Such systems are subject to failure anytime and error checking is not usually reliable. In those cases,

    you should use exception handlers and try to recover from error.

    Do not write very large try-catch blocks. If required, write separate try-catch for each task you performand enclose only the specific piece of code inside the try-catch. This will help you find which piece ofcode generated the exception and you can give specific error message to the user.

    Use log4net as default library for logging. Use levels (DEBUG, INFO, WARN, ERROR) properly.

    Use the level DEBUGwhen you need to check parameter values in a method.

    Use the level INFOwhen you need to inform about the normal flow of the method.

    Use the level WARNwhen you need to inform about that the main flow goes for a different path. e.gSomething does not go entirely well.

    .Use the level ERRORto log exceptions mainly.

    Always ask is the level you want to use is enabled before log. It increase the performance.

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    25/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 25 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    Good:if(Log.IsInfoEnabled)

    Log.InfoFormat("Tu [{0}] match with storage plan ID [{1}].", tuName, match.Id);

    Not Good:

    Log.WarnFormat("No Plan movements for Bay..

    Always use the Format method for each level when you need to log values from variables.

    Good:

    Log.InfoFormat("Tu {0} match with storage plan ID {1}.", tuName, match.Id);

    Not Good:

    Log.Info("Tu + tuName + match with storage plan ID" + match.Id);

    Always include the exception object in the Error level. Use string.Format when you need to add

    variables to the error log.

    Good:

    catch (Exceptionex){

    Log.Error("Exection trying to do something", ex);throw;

    }

    catch (Exceptionex){

    Log.Error(string.Format("Exection trying to do something. Value {0}",value), ex);throw;

    }

  • 8/10/2019 C_Sharp Coding Standards and Best Practices-v1.2.pdf

    26/26

    Siemens C# Coding Standards and Best Practices Date: 2012-08-21

    I MT Page 26 of 26

    Copyright Siemens SA, 2012. All Rights Reserved.

    Not Good:

    catch (Exceptionex){

    Log.Error("Exection trying to do something"+ ex.Message);throw;

    }

    catch (Exceptionex){

    Log.Error("Exection trying to do something. Value "+value.ToString() + ex.ToString());throw;

    }