1. Name specification
1. Using the Pascal Casing Definition Type and Method Public Class SomeClass {Public SomeMethod () {}} 2. Using Camel Casing Defining Local Variable Name and Method Parameters Int Number; Void Mymethod (Int Somenumber) {} 3. Using "I" prefix Define interface name interface iMyinterface {..} 4. Use the "M_" prefix to define private member variables public class someclass {private int m_number;} 5. The property class uses "Attribute" as a suffix 6. Exception. "Is the suffix. 7. Method Naming uses verb phrases, such as showdialog () 8. Method with return values should describe the return value in the name, such as getObjectState () 9. Generally, when the naming parameters plus TYPE. This will increase the code Reading // Correct: Public Class LinkedList
16. Use interests, such as product names, company names, etc. 17. Avoid using the full name of the type, replace it with "using" declaration .18. Avoid "USING" declaration in the namespace. 19. All frames Namespaces in front, custom or third-party namespaces are packet .using system; using system.collections; using system.componentmodel; use system.data; ustrib; 20. file name should reflect it The included class. 21. Always put "{" in a new line. 22. Use anonymous method to simulate the code structure of normal methods, arrange anonymous agents (with Anonymous methods mimic the code layout of a regular method, aligned with the the Anonymous Delegate Declaration.a) Comply with placing an open curly brace in a new line 2 Coding Practices1. Using the C # predefined types better than the unique names of the system space, for example: Object instead of ObjectString instead of stringint instead of int322. Avoid multiple The class is placed in a file. 3. One file should belong to a namespace instead of multiple.4. Avoid a file more than 500 rows (excluding the automatically generated code) .5. Avoid more than 25 lines. 6. More than 80 characters. 7. Do not change the automatically generated code. 9. Avoid Comments That Explain The Obvious.10. Code Should Be Self Explanator. Good Code with Readable Variable And MethodNames Should Not Require Comments.11 . Document only operational assumptions, algorithm insights etc.12. Avoid method-level documentation.a) Use extensive external documentation for API documentation.b) Use method-level comments only as tool tips for other developers.13. Never hard-code a numeric value, always declare a constant instead.14 Assert every assumption.15 On average, every fifth line is an assertion.using System.Diagnostics;.. object GetObject () {...} object obj = GetObject (); Debug.Assert ( Obj! = null);
16. Make only the most necessary types public, mark others as internal.17. Always use zero-based arrays.18. Avoid providing explicit values for enums.19. Avoid specifying a type for an enum (like long) .20. Never use goto unless in a switch statement fall-through.www.idesign.net August 2003- 6 - © 2003 IDesign Inc. All rights reserved21 Avoid function calls in Boolean conditional statements Assign into local variablesand check on them:.. bool IsEverythingOK () {...} // avoid: if (ISeverythingok ()) {...} // instead: BOOL OK = ISEVERYTHINGOK (); if (ok) {...} 22. ALWAYS Explicitly Initialize An Array Of Reference Types Using A for loop.public Class myclass {} myclass [] array = new myclass [100]; for (int index = 0; index } 25. Avoid error code as methods return values.26. Do not use the new inheritance qualifier. Use override instead.27. Minimize code in application assemblies (EXE client assemblies), use class librariesinstead to contain business logic.28. Never hardcode strings that will be presented to end users. use resources instead.29. Never hardcode strings that might change based on deployment such as connectionstrings.30. Never use unsafe code unless when using interop.31. Always use interfaces.a) See Chapters 1 . and 3 in Programming .NET Components.32 Avoid multiple Main () methods in a single assembly.www.idesign.net August 2003- 7 -.. © 2003 IDesign Inc. All rights reserved33 Avoid explicit casting Use the as operator to defensively cast to a type.Dog dog = new GermanShepherd (); GermanShepherd shepherd = dog as GermanShepherd;.. if (! shepherd = null) {...} 34 Never assume a type supports an interface Defensively query for that interface.SomeType obj1; IMyInterface Obj2; / * Some code to initialize Obj1, then: * / obj2 = obj1 as IMyInterface; if (obj2 = null!) {obj2.Method1 ();} else {// Handle error in expected interface} 35 Do not provide public or protected member variables Use properties instead... . 36. Do not provide public event member variables Use event accessors instead.public class MySource {MyDelegate m_NumberChangedEvent; public event MyDelegate NumberChangedEvent {add {m_NumberChangedEvent = value;} remove {m_NumberChangedEvent - = value; }}} 37 Classes and interfaces should have at least 2:. 1 ratio of methods to properties.38 Avoid interfaces with one member.39 Strive to have 3-5 members per interface.40 No more than 20 members per interface... .a) 12 is probably a practical limit.41. Avoid events as interface members.42. Avoid abstract methods, use interfaces instead.43. Always prefer using C # generics in data structures.44. Expose interfaces on class hierarchies.a) See Chapter 3 in Programming .NET Components.www.idesign.net August 2003- 8 -.. © 2003 IDesign Inc. All rights reserved45 Prefer using explicit interface implementation.a) See Chapter 3 in Programming .NET Components.46 Always mark public and protected methods as virtual in a non sealed class.47. When building a long string, use StringBuilder, not string.48. Always use a curly brace scope in an if statement, even if it conditions a singlestatement.49. With delegates as class MEMBERS: a) COPY A DELEGATE TO A LOCAL VARIABLE BEFORE PUBLISHING TO AVOID Concurrency racecondition.b) Always check a delegate for null before invoking it.public class MySource {public event EventHandler MyEvent; public void FireEvent () {EventHandler temp = MyEvent;! if (temp = null) {temp (this, EventArgs.Empty) }}} 50. Always Have a Default Case in a switch statement this assert number = someMethod (); switch (number) {Case 1: Trace.writeline ("Case 1:"); Break; Case 2: Trace.writeline ("CASE 2:"); Break; Default: Debug.Assert (false); Break; } 51. Avoid providing methods on structures.a) Parameterized constructors are encouraged.b) Can overload operators.52. Always provide a static constructor when providing static member variables.53. Every line of code should be walked through in a "white box .. "testing manner.54 Avoid code that relies on an assembly running from a particular location.55 Do not use late-binding invocation when early-binding is possible.www.idesign.net August 2003- 9 - © 2003 IDesign Inc. All rights reserved56. Avoid using the trinary conditional operator.57. Do not use the this reference unless invoking another constructor from within aconstructor.//Example of proper use of 'this'public class MyClass {public MyClass (string message) {} public MyClass ():. this ( "hello") {}} 58 use the EventsHelper class defined in Programming .NET Components topublish events defensively.59 use application logging and tracing.60 Do not use the base word to access base class members.. UnsS you wish to resolvea conflict with a SUBC lasses member of the same name or when invoking a base classconstructor.//Example of proper use of 'base'public class Dog {public Dog (string name) {} virtual public void Bark (int howLong) {}} public class GermanShepherd: Dog. {public GermanShepherd (string name): base (name) {} override public void Bark (int howLong) {base.Bark (howLong);}} 61 Implement Dispose () and Finalize () methods based on the template inChapter 4 of Programming .NET Components.62. Avoid casting to and from System.Object in code that uses generics.63. Use the const directive only on natural constants such as the number of days ofweek. Avoid using const on read only variables. For that Use the readonlydirective.public class myclass {public ready- Number public MyClass (int someValue) {Number = someValue;} const int DaysInWeek = 7;} www.idesign.net August 20033 Project Settings and Project Structure1 Always build your project with warning level 42. Treat warning as errors in Release build (note. that this is not the default of VS.NET) .a) Although it is optional, this standard recommend treating warnings as errors indebug builds as well.3 Never suppress specific compiler warnings.- 11 -. © 2003 IDesign Inc. All rights reserved4 . Always explicitly state your supported runtime versions in the applicationconfiguration file. See Chapter 5 in Programming .NET Components. xml version = "1.0"?> }} Return result;.} 14 Avoid tampering with exception handling using the Exception window (Debug | Exceptions) .15 Strive to uniform version numbers on all assemblies and clients in same logicalapplication (typically a solution) .16 Name your VS... NET application configuration file as App.Config, and include it inthe project.17. Avoid explicit code exclusion of method calls (# if ... # endif). Use conditionalmethods instead.public class MyClass {[Conditional ( "MySpecialCondition")] public void MyMethod () {}} www.idesign.net August 200318. Modify VS.NET default project structure to your project standard layout, and applyuniform structure for project folders and files.19 Link all solution-wide information to a global shared file.: - 13 - © 2003 Idesign Inc. All Rights Reserved20. INSERT SPACES for Tabs. Uses | Options | Text Editor | C # | Tabswww.ideSign.NET August 2003-4 © 2003 Idesign Inc. All Rights . reserved21 Release build should contain debug symbols.22 Always sign your assemblies, including the client applications.23 Always sign interop assemblies with the project's SNK filewww.idesign.net August 2003- 15 -.. © 2003 IDesign Inc. All rights reserved4 Framework Specific Guidelines4.1 Data access1. Always use type-safe data sets. Avoid raw ADO.NET.2. Always use transactions when accessing a database.3. Always use transaction isolation level set to Serializable.a) Requires management decision to use anything else.4. Do not use the Server Explorer to drop connections on windows forms, ASP.NETforms or web services. Doing so couples the presentation tier to the data tier.5. Avoid SQL Server authentication.a) use Windows authentication instead.6 . Run Components Accessing SQL Server Under Sep arate identity from that of thecalling client.7. Always warp your stored procedures in a high level, type safe class. Only that classinvokes the stored procedures.8. Avoid putting any logic inside a stored procedure.a) If there is an IF inside a stored procedure, you are doing something wrong.4.2 ASP.NET and Web Services1. Avoid putting code in ASPX files of ASP.NET. All code should be in the codebehindclass.2. code in code behind class of ASP.NET should call Other Components Rather Than Logic.3. in Both ASP.NET Pages and Web Services, Wrap A Session Variables in a localproperty. Only that property is allowed to access the session variable, and the rest ofthe code uses the property, not the session variable.4. Avoid setting to True the Auto-Postback property of server controls in ASP.NET.5. In transactional pages or web services, always store session in SQL server.6. Turn on Smart Navigation for ASP.NET pages.7. Strive to provide interfaces for web servicesa) See Appendix A of Programming .NET Comp onents.8. Always provide namespace and service description for web services.9. Always provide a description for web methods.10. When adding a web service reference, provide meaningful name for the location.11. Always modify client-side web service wrapper class to support cookies.a) You have no way of knowing whether the service uses Session state or not.www.idesign.net August 2003- 16 -. © 2003 IDesign Inc. All rights reserved4.3 Serialization1 Always mark non-sealed classes as Serializable.2 Always mark un-serializable. Member variables as non serializable.3. Always . Mark delegates on a serialized class as non-serializable [Serializable] public class MyClass {[field: NonSerialized] public event MyDelegate Delegate;} 4.4 Multithreading1 Use Synchronization Domains See Chapter 8 in Programming .NET Components.a) Avoid manual synchronization.. , because they often lead to deadlocks and raceconditions.2. Never call outside your synchronization domain.3. Manage asynchronous call completion on a callback method.a) Do not wait, poll, or block for completion.4. Always name your threads. a) Name is traces in the debugger threads window, Making a debug session moreproductive.thread currentthread = thread. Currentthread; string threadname = "main ui thread"; currentthread.name = threadName; 5. Do not call suspend () or resume () on a thread.sleep (). A) thread.sleep 0) is acceptable optimization technique to force a contextswitch.b) Thread.Sleep () is acceptable in testing or simulation code.7. Do not call Thread.SpinWait (). 8. Do not call Thread.Abort () to terminate threads .a) Use a synchronization object instead to signal the thread to terminate. SeeChapter 8 in Programming .NET Components.9. Avoid explicitly setting thread priority to control execution.a) Can set thread priority based on task semantic, such as bellow normal for ascreen saver.10. Do not read the value of the thread state property.a) Use Thread.IsAlive () to determine whether the thread is dead.11. Do not rely on setting the thread type to background thread for application shutdown.a USE A WATCHDOG or other monitoring entity to deterministical kill threads.12. Do Not Use Thread Local Storage Unless Thread affinity is guaranteed.www.idesign.net August 2003- 17 -. © 2003 IDesign Inc. All rights reserved13 Never call Thread.Join () without checking that you are not joining your ownthread.void WaitForThreadToDie (Thread thread) {Debug.Assert (Thread.CurrentThread.GetHashCode () = tread.GetHashCode ()!); thread.Join ();..} 14 Always use the lock () statement rather than explicit Monitor manipulation.15 Always encapsulate the lock () statement inside the Object it protects. public class MyClass {public void DoSomething () {lock (this) {// Do Something}}} a) Can use synchronized methods instead of writing the lock () statementyourself.16. Avoid fragmented locking (see Chapter 8 of Programming .NET Components) .17. Avoid using a Monitor to wait or pulse objects. use manual or auto-reset eventsinstead.18. Always release a Mutex inside a finally statement to handle exceptions.19. Do not use volatile variables. Lock your object or fields instead to guaranteedeterministic and thread-safe access.4.5 Remoting1. Prefer administrative configuration to programmatic configuration.2. Always implement IDisposable on a single call objects.3. Always prefer TCP channel and binary format when using remoting.a) Unless a firewall is present .4 Always provide a null lease for a singleton object.public class MySingleton:.. MarshalByRefObject {public override object InitializeLifetimeService () {return null;}} 5 always provide a sponsor for a client activated object Sponsor should return i. nitiallease timed.a) See Chapter 10 of Programming .NET Components.www.idesign.net August 2003- 18 -.. © 2003 IDesign Inc. All rights reserved6 Always unregister a sponsor on client application shutdown.7 Always put remote objects in class libraries.8. Avoid using SoapSuds.9. Avoid hosting in IIS.10. Avoid using uni-directional channels.11. Always load a remoting configuration file in Main () even if the file is empty, andthe application does not use remoting. a) Allow the option of remoting some types later on post deployment, andchanging the application topology.static void Main () {RemotingConfiguration.Configure ( "MyApp.exe.config"); / * Rest of Main () * /} 12. Avoid Using Activator.getObject () Andactivator. CreateiInstance () for remote objects activation Use newinstead.13 Always register port 0 on the client side, to allow callbacks.14 Always elevate type filtering to full on both client and host to allow callbacks.Host Config file:... All rights reserved4.6 Security1. Always demand your own strong name on assemblies and components that areprivate to the application, but are public (so that only you can use them) .public class PublicKeys {public const string MyCompany = "1234567894800000940000000602000000240000" " 52534131000400000100010007D1FA57C4AED9F0 " " A32E84AA0FAEFD0DE9E8FD6AEC8F87FB03766C83 " " 4C99921EB23BE79AD9D5DCC1DD9AD23613210290 " " 0B723CF980957FC4E177108FC607774F29E8320E " " 92EA05ECE4E821C0A5EFE8F1645C4C0C93C1AB99 " " 285D622CAA652C1DFAD63D745D6F2DE5F17E5EAF " " 0FC4963D261C8A12436518206DC093344D5AD293 ";} [StrongNameIdentityPermission (SecurityAction.LinkDemand, PublicKey = PublicKeys.MyCompany)] public class MyClass {...} 2. Apply encryption and security protection on application configuration files.3. Assert unmanaged code permission, and demand appropriate permission instead.4. On server machines deploy code-access security policy that grants only Microsoft, ECMA and self (identified by strong name) full trust .a) All OTH er code is implicitly granted nothing.5. On client machine, deploy a security policy which grants client application only thepermissions to call back the server and to potentially display user interface.a) Client application identified by strong name.6. Always refuse at the assembly level all permissions not required to perform task athand.a) The counter a luring attack [assembly: UIPermission (SecurityAction.RequestRefuse, Window = UIPermissionWindow.AllWindows)].. 7 Always set the principal policy in every Main () method to Windowspublic Class myclass {static void main () {appdomain currentdomain = thread.