public static object CloneObject(object obj)
{
using (System.IO.MemoryStream memStream = new MemoryStream())
{
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(null,
new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Clone));
binaryFormatter.Serialize(memStream, obj);
memStream.Seek(0, SeekOrigin.Begin);
return binaryFormatter.Deserialize(memStream);
}
}
Object Cloning c#.net
How to deliver multiple dlls and exe as a single file
Scenario: You are developing a dotnet appliation, For that you are adding some external dlls ex:Office.dll. Normally we need to build the application and provide the directory containing dlls and exe for the customer. How to deliver all the files as a single pack. Is it possible if so how?
Solution: Download the ilmerge.exe from the below link and install it in your machine.
http://www.microsoft.com/downloads/details.aspx?FamilyID=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en
After Building your application go to the command prompt and give the below syntax.
"path<ilmerge.exe>" /out:"($TargetDir)ExpectedApplicationname.exe" "($TargetPath)" *.dll.....
example for the arguments:
"c:\programfiles\ilmerge\ilmerge.exe" /out:"c:\myApp\SingleFile.EXE" "c:\myApp\bin\debug\myApp.exe" "c:\myApp\bin\debug\office.exe"
(OR)
You can also provide this command in the postbuild command so the singlefile will created directly when you build the application.
BackgroundWorker Control
The BackgroundWorker class allows you to run an operation on a separate, dedicated thread.
Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running( i.e it seems like white faded screen ). In such a case this background worker will helpful so the fading are avoided bcoz it was running under seperate dedicated thread.
Three events available in backgroundworker.
1.DoWork: In which we need write the business logic
2.Runworkercompleted: This event automatically fired when the bgworker completes its process
3.Progresschanged: from which we can get the percentage of completed process.
To start the bgworker use the method RunWorkerAsync()
Consider the code snippet below create a win form and select 2 button as named BgworkerButton,NormalButton add a background worker as backgroundWorker1 and test it.
string str = string.Empty;
public Form1()
{
InitializeComponent();
}
private void BgworkerButton_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 10000; i++)
str = str + " bg" + i.ToString();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Completed");
}
private void NormalButton_Click(object sender, EventArgs e)
{
for (int i = 1; i <= 10000; i++)
str = str + " " + i.ToString();
MessageBox.Show("Completed");
}
Compare Generic.List vs Array
Consider that you r in a situation to use some collection object. What type you will prefer Generic.list or Array
Advantage of generic is, it is easy to handle. use the add, remove and new extension methods in .net2008 but which is efficient.
(i) for( int i = 0; i < 5000000; i++ )
{
for( int j = 0; j < Array.Length; j++ )
{
Array[j] = j;
}
}
(ii)for( int i = 0; i < 5000000; i++ )
{
for( int j = 0; j < List.Count; j++ )
{
List[j] = j;
}
}
the time for the execution is The results where 2620 for the Array and 13200 for the List in terms of nanoseconds.
The reasons are
1. it has to do with the memory not necessarily being contiguous, and so the lookup is slightly more complex
2. List generic version is actually making function calls in the generated code this will understand if u saw the IL code for the above two cases but not in case of array.
3. The List<T> class uses an array internally, and will do effectively the same operation as Array.Resize(). The only real difference between the two is that List<T> always doubles the size of the storage, so that you need to resize fewer and fewer times as the data gets larger. Of course, you could always use that strategy when using Array.Resize() as well,
preserving Array elements using c#.net
Consider the two arrays:
string[] str = new string[1];
str[0] = "str";
string[] str1 = new string[2];
str1[0] = "str1";
str1[1] = "str2";
To append an two arraycollections:
str = str.Concat(str1).ToArray(); //the result was stored in the str array. this will work only in .net 2008
To add new element in the array:
Array.Resize(ref str, newSize);
str[newSize-1] = "newvalue";
Convert string to datatime format
1.
string str = "24/10/2008";
DateTime dt = DateTime.ParseExact(str, "dd/MM/yyyy",
Thread.CurrentThread.CurrentCulture);
2.DateTime date = System.DateTime.ParseExact(str, "dd/MM/yyyy", null);
DateTime date = System.DateTime.ParseExact(str, "HH:mm:ss", null);
Effect of Double in .net
Did u feel its a best way to use double in your application.
Test the following scenario:
double a=0.3;
double b=0.1+0.1+0.1;(or)0.2+0.1;
if(a==b)
MessageBox.Show(r u great?);
else
MessageBox.Show(u r great!);
if u put float u wont get the same output.
There is not only problem in using this format. but there are lot of issues and doubt while using double datatype. So consider twice before using double in your application
Solution: We cant say it as an error. in Java also the same thing will happen. its some double precision format.
Better using decimal is a good solution.
Linq for XML .net 2008
Language integrated query for xml
Its very similar to .net 2005 xml processing. the feature added here in .net 2008 is linq.
We can query into the xml elements directly like sql queries.
Also we do the same task with easy and less line of codes(loc) using linq. We can also write events for nodes so any triger on the node are watchable.
For more and through ref search : http://msdn.microsoft.com/en-us/library/bb308960.aspx
System.Windows.Forms.Timer vs. System.Threading.Timer vs. System.Timers.Timer
| Feature description | System.Timers.Timer | System.Threading.Timer | System.Windows.Forms.Timer |
| Support for adding and removing listeners after the timer is instantiated. | Yes | No | Yes |
| Supports call backs on the user-interface thread | Yes | No | Yes |
| Calls back from threads obtained from the thread pool | Yes | Yes | No |
| Supports drag-and-drop in the Windows Forms Designer | Yes | No | Yes |
| Suitable for running in a server multi-threaded environment | Yes | Yes | No |
| Includes support for passing arbitrary state from the timer initialization to the callback. | No | Yes | No |
| Implements IDisposable | Yes | Yes | Yes |
| Supports one-off callbacks as well as periodic repeating callbacks | Yes | Yes | Yes |
| Accessible across application domain boundaries | Yes | Yes | Yes |
| Supports IComponent – hostable in an IContainer | Yes | No | Yes |
Using the System.Windows.Forms.Timer is a relatively obvious choice for user interface programming. Choosing between the other two options is less obvious and generally the choice between the two is insignificant. If hosting within an IContainer is necessary then obviously System.Timers.Timer is the right choice. However, if no specific System.Timers.Timer feature is required, then I suggest choosing System.Threading.Timer by default, simply because it is a slightly lighter weight implementation.
Labels: C#
index -1 does not have a value in datagridview
scenario: The grid was bound to a simple object collection. The object contained
string and decimal properties, nothing to fancy. When an item was added to
the collection I would databind as follows (this happened on each item
"Add"):
If I added an item after I deleted all the items in
the grid (collection) and try to select it the grid would bomb out with the
following error: "Index -1 does not have a value".
myObject.CollectionProperty.Add(myBasicObject);
dgvGrid.DataSource = myObject.CollectionProperty;
This will cause the above error
solution:
set the simple object collection in to a binding source and set the resetbinding to false like below
Againg assign the binding source to the grid
bsBindingSource.ResetBindings(false);
bsBindingSource.DataSource = myObject.CollectionProperty;
dgvGrid.DataSource = bsBindingSource;
to the Add routine, just after the object is added to the collection.
Viola! Problem was fixed, and I no longer needed to bind the grid twice. I
was able to make the binding work now with just this:
Labels: C#
Chanakya's Quotes - Worth reading a million times...
***************************************************
"A person should not be too honest.
Straight trees are cut first
and Honest people are victimised first."
Chanakya quotes (Indian politician, strategist and writer, 350 BC 75 BC)
***************************************************
"Even if a snake is not poisonous,
it should pretend to be venomous."
Chanakya quotes (Indian politician, strategist and writer, 350 BC-275 BC)
***************************************************
"The biggest guru-mantra is: Never share your secrets with anybody. ! It will destroy you."
Chanakya quotes (Indian politician, strategist and writer, 350 BC-275 BC)
***************************************************
"There is some self-interest behind every friendship.
There is no Friendship without self-interests.
This is a bitter truth."
Chanakya quotes (Indian politician, strategist and writer, 350 BC-275 BC)
***************************************************
"Before you start some work, always ask yourself three questions - Why am I doing it, What the results might be and Will I be successful. Only when you think deeply
and find satisfactory answers to these questions, go ahead."
Chanakya quotes (Indian politician, strategist and writer, 350 BC-275 BC)
***************************************************
"As soon as the fear approaches near, attack and destroy it."
Chanakya quotes (Indian politician, strategist and writer, 350 BC-275 BC)
***************************************************
"Once you start a working on something,
don't be afraid of failure and
don't abandon it.
People who work sincerely are the happiest."
Chanakya quotes (Indian politician, strategist and writer, 350 BC-275BC)
***************************************************
"The fragrance of flowers spreads
only in the direction of the wind.
But the goodness of a person spreads in all direction."
Chanakya quotes (Indian politician, strategist and writer, 350 BC-275BC)
***************************************************
"A man is great by deeds, not by birth."
Chanakya quotes (Indian politician, strategist and writer, 350 BC-275BC)
***************************************************
"Treat your kid like a darling for the first five years.
For the next five years, scold them.
By the time they turn sixteen, treat them like a friend.
Your grown up children are your best friends."
Chanakya quotes (Indian politician, strategist and writer, 350 BC-275BC)
***************************************************
"Books are as useful to a stupid person
as a mirror is useful to a blind person."
Chanakya quotes (Indian politician, strategist and writer, 350 BC-275BC)
***************************************************
"Education is the best friend.
An educated person is respected everywhere.
Education beats the beauty and the youth."
Chanakya quotes (Indian politician, strategist and writer, 350 BC-275BC)
Labels: Commercial
Keyboard Shortcuts for .Net Programming
1. New Project (Ctrl+Shift+N )
2. Open Project/Solution (Ctrl+Shift+O)
3. Open File (Ctrl+O)
4. Save (Ctrl+S)
5. Save As (Ctrl+Shift+S)
6. Print (Ctrl+P)
Edit
7. Undo (Ctrl+Z)
8. Redo (Ctrl+Y)
9. Cut (Ctrl+X)
10. Copy (Ctrl+C)
11. Paste (Ctrl+V)
12. Cycle Clipboard Ring (Ctrl+Shift+V)
13. Select All (Ctrl+A)
14. Quick Find (Ctrl+F)
15. Quick Replace (Ctrl+H)
16. Find in Files (Ctrl+Shift+F)
17. Replace in Files (Ctrl+Shift+H)
18. Find Symbol (Alt+F12)
19. Format Document (Ctrl+E,D)
20. Format Selection (Ctrl+E,F)
21. Make Uppercase (Ctrl+Shift+U)
22. Make Lowercase (Ctrl+U)
23. Delete Horizontal White Space (Ctrl+E, \)
24. View White Space (Ctrl+E,S)
25. Word Wrap (Ctrl+E,W)
26. Incremental Search (Ctrl+I)
27. Comment Selection (Ctrl+K,C)
28. Uncomment Selection (Ctrl+K,U)
29. Toggle Bookmark (Ctrl+K,K)
30. Enable Bookmark (Ctrl+B,E)
31. Previous Bookmark (Ctrl+K,P)
32. Next Bookmark (Ctrl+K, N)
33. Clear Bookmarks (Ctrl+K,K)
34. Add Task List Shortcut (Ctrl+E,T)
35. Hide Selection (Ctrl+M, Ctrl+H)
36. Toggle Outlining Expansion (Ctrl+M,M)
37. Toggle All Outlining (Ctrl+M,L)
38. Stop Outlining (Ctrl+M,P)
39. Stop Hiding Current (Ctrl+M, Ctrl+U)
40. Generate Method Stub (Ctrl+K,M)
41. List Members (Ctrl+K,L)
42. Parameter Info (Ctrl+K,P)
43. Complete Word (Ctrl+K,W)
44. Insert Snippet (Ctrl+K,X)
45. Surround With (Ctrl+K,S)
View
46. Code (F7)
47. Designer (Shift+F7)
48. Server Explorer (Ctrl+W,L)
49. Class View (Ctrl+W,C)
50. Code Definition Window (Ctrl+W,D)
51. Object Browser (Ctrl+W,J)
52. Error List (Ctrl+W,E)
53. Output (Ctrl+W,O)
54. Properties Window (Ctrl+W,P)
55. Task List (Ctrl+W,T)
56. Toolbox (Ctrl+W,X)
57. Find Symbol Results (Ctrl+W,Q)
58. Bookmark Window (Ctrl+W,B)
59. Command Window (Ctrl+W,A)
60. Document Outline (Ctrl+W,U)
61. Resource View (Ctrl+W,R)
62. Macro Explorer (Alt+F8)
63. Web Browser (Ctrl+W,W)
64. Full Screen (Shift+Alt+Enter)
65. Pending Checkins (Ctrl+W,G)
66. Navigate Backward (Ctrl+-)
67. Navigate Forward (Ctrl+Shift+-)
68. Property Pages (Shift+F4)
Refactor
69. Rename (F2)
70. Extract Method (Ctrl+R,M)
71. Encapsulate Field (Ctrl+R,E)
72. Promote Local Variable to Parameter (Ctrl+R,P)
73. Remove Parameters (Ctrl+R,V)
74. Reorder parameters (Ctrl+R,O)
Website
75. Add New Item (Ctrl+Shift+A)
76. Add Existing Item (Shift+Alt+A)
Build
77. Build Solution (F6)
78. Build Web Site (Shift+F6)
Debug
79. Breakpoints (Ctrl+D,B)
80. Immediate (Ctrl+D,I)
81. Start Debugging (F5)
82. Start without Debugging (Ctrl+F5)
83. Exceptions (Ctrl+D,E)
84. Step Into (F11)
85. Step Over (F10)
86. Break at Function (Ctrl+D,N)
87. Delete All Breakpoints (Ctrl+Shift+F9)
Tools
88. Attach to Process (Ctrl+Alt+P)
89. Code Snippets Manager (Ctrl+K, Ctrl+B)
90. Run TemporaryMacro (Ctrl+Shift+P)
91. Record TemporaryMacro (Ctrl+Shift+R)
92. Macro Explorer (Alt+F8)
93. Macros IDE (Alt+F11)
Help
94. How Do I (Ctrl+F1,H)
95. Search (Ctrl+F1,S)
96. Contents (Ctrl+F1,C)
97. Index (Ctrl+F1,I)
98. Help Favourites (Ctrl+F1,F)
99. Dynamic Help (Ctrl+F1,D)
100. Index Results (Ctrl+F1,T)
Labels: C#
.net 2008 features
1. LINQ Support
LINQ essentially is the composition of many standard query operators that allow you to work with data in a more intuitive way regardless.
The benefits of using LINQ are significant – Compile time checking C# language queries, and the ability to debug step by step through queries.
2. Expression Blend Support
Expression blend is XAML generator tool for silverlight applications. You can install Expression blend as an embedded plug-in to Visual Studio 2008. By this you can get extensive web designer and JavaScript tool.
3. Windows Presentation Foundation
WPF provides you an extensive graphic functionality you never seen these before. Visual Studio 2008 contains plenty of WPF Windows Presentation Foundation Library templates. By this a visual developer who is new to .NET, C# and VB.NET can easily develop the 2D and 3D graphic applications.
Visual Studio 2008 provides free game development library kits for games developers. currently this game development kits are available for C++ and also 2D/3D Dark Matter one image and sounds sets.
4. VS 2008 Multi-Targeting Support
Earlier you were not able to working with .NET 1.1 applications directly in visual studio 2005. Now in Visual studio 2008 you are able to create, run, debug the .NET 2.0, .NET 3.0 and .NET 3.5 applications. You can also deploy .NET 2.0 applications in the machines which contains only .NET 2.0 not .NET 3.x.
5. AJAX support for ASP.NET
Previously developer has to install AJAX control library separately that does not come from VS, but now if you install Visual Studio 2008, you can built-in AJAX control library. This Ajax Library contains plenty of rich AJAX controls like Menu, TreeView, webparts and also these components support JSON and VS 2008 contains in built ASP.NET AJAX Control Extenders.
6. JavaScript Debugging Support
Since starting of web development all the developers got frustration with solving javascript errors. Debugging the error in javascript is very difficult. Now Visual Studio 2008 makes it is simpler with javascript debugging. You can set break points and run the javaScript step by step and you can watch the local variables when you were debugging the javascript and solution explorer provides javascript document navigation support.
7. Nested Master Page Support
Already Visual Studio 2005 supports nested master pages concept with .NET 2.0, but the problem with this Visual Studio 2005 that pages based on nested masters can't be edited using WYSIWYG web designer. But now in VS 2008 you can even edit the nested master pages.
8. LINQ Intellisense and Javascript Intellisense support for silverlight applications
Most happy part for .NET developers is Visual Studio 2008 contains intellisense support for javascript. Javascript Intellisense makes developers life easy when writing client side validation, AJAX applications and also when writing Silverlight applications
Intellisense Support: When we are writing the LINQ Query VS provides LINQ query syntax as tool tips.
9. Organize Imports or Usings: We have Organize Imports feature already in Eclipse. SInce many days I have been waiting for this feature even in VS. Now VS contains Organize Imports feature which removes unnecessary namespaces which you have imported. You can select all the namespaces and right click on it, then you can get context menu with Organize imports options like "Remove Unused Usings", "Sort Usings", "Remove and Sort". Refactoring support for new .NET 3.x features like Anonymous types, Extension Methods, Lambda Expressions.
10. Intellisense Filtering: Earlier in VS 2005 when we were typing with intellisense box all the items were being displayed. For example If we type the letter 'K' then intellisense takes you to the items starts with 'K' but also all other items will be presented in intellisense box. Now in VS 2008 if you press 'K' only the items starts with 'K' will be filtered and displayed.
11. Intellisense Box display position
Earlier in some cases when you were typing the an object name and pressing . (period) then intellisense was being displayed in the position of the object which you have typed. Here the code which we type will go back to the dropdown, in this case sometimes programmer may disturb to what he was typing. Now in VS 2008 If you hold the Ctrl key while the intellisense is dropping down then intellisense box will become semi-transparent mode.
12. Visual Studio 2008 Split View
VS 205 has a feature show both design and source code in single window. but both the windows tiles horizontally. In VS 2008 we can configure this split view feature to vertically, this allows developers to use maximum screen on laptops and wide-screen monitors.
Here one of the good feature is if you select any HTML or ASP markup text in source window automatically corresponding item will be selected in design window.
13. HTML JavaScript warnings, not as errors: VS 2005 mixes HTML errors and C# and VB.NET errors and shows in one window. Now VS 2008 separates this and shows javascript and HTML errors as warnings. But this is configurable feature.
14. Debugging .NET Framework Library Source Code:
Now in VS 2008 you can debug the source code of .NET Framework Library methods. Lets say If you want to debug the DataBind() method of DataGrid control you can place a debugging point over there and continue with debug the source code of DataBind() method.
15. In built Silverlight Library
Earlier we used to install silverlight SDK separately, Now in VS 2008 it is inbuilt, with this you can create, debug and deploy the silverlight applications.
16. Visual Studio LINQ Designer
Already you know in VS 2005 we have inbuilt SQL Server IDE feature. by this you no need to use any other tools like SQL Server Query Analyzer and SQL Server Enterprise Manger. You have directly database explorer by this you can create connections to your database and you can view the tables and stored procedures in VS IDE itself. But now in VS 2008 it has View Designer window capability with LINQ-to-SQL.
17. Inbuilt C++ SDK
Earlier It was so difficult to download and configure the C++ SDK Libraries and tools for developing windows based applications. Now it is inbuilt with VS 2008 and configurable
18. Multilingual User Interface Architecture - MUI
MUI is an architecture contains packages from Microsoft Windows and Microsoft Office libraries. This supports the user to change the text language display as he wish.
Visual Studio is now in English, Spanish, French, German, Italian, Chinese Simplified, Chinese Traditional, Japanese, and Korean. Over the next couple of months. Microsoft is reengineering the MUI which supports nine local languages then you can even view Visual studio in other 9 local languages.
19. Microsoft Popfly Support
Microsoft Popfly explorer is an add-on to VS 2008, by this directly you can deploy or hosting the Silverlight applications and Marshup objects
20. Free Tools and Resources
People may feel that I am a promoter to Visual Studio 2008 as a salesman, but we get plenty of free resources and free tools with Visual Studio 2008.
Labels: C#
best practices for Good programming
best practices for Good programming
2.1.1Avoid having too large files.
If a file has more than 300~400 lines of code, you must consider refactoring code into helper classes.
2.1.2Avoid writing very long methods.
A method should typically have 1~25 lines of code. If a method has more than 25 lines of code, you must consider re factoring into separate methods.
2.1.3White Space
Blank lines improve readability by setting off sections of code that are logically related.
Two blank lines should always be used between sections of a source file. That is, two blank lines should follow:
the opening comment
the package statement
the import statements
the class and interface declaration
One blank line should always be used in the following circumstances:
Between methods
Between the local variables in a method and its first statement
Before a block or single-line comment.
Between logical sections inside a method to improve readability.
Use common sense and don't be afraid to put blank lines!
2.1.4Blank Spaces
Blank spaces should be used in the following circumstances:
A blank space should appear after commas in argument lists.
All binary operators except. Should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment ("++"), and decrement ("--") from their operands.
The expressions in a "for" statement should be separated by blank spaces.
example:
public void aMethod(int a, int b, int c, int d) { a += c + d; a = (a + b) / (c * d); printSize("size is " + foo); for(expr1; expr2; expr3) { /* No Body */ } }
2.1.5Parentheses
It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems
if(a == b && c == d) // AVOID! if((a == b) && (c == d)) // RIGHT
2.1.6Naming Guidelines
A consistent naming pattern is one of the most important elements of predictability and discoverability in a managed class library.
2.1.6.1Capitalization Styles
Describes the Pascal case, camel case, and uppercase capitalization styles to use to name identifiers in class libraries.
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:
BackColor
Camel case
The first letter of an identifier is lowercase and the first letter of each subsequent concatenated word is capitalized.
Example:
backColor
Uppercase
All letters in the identifier are capitalized. Use this convention only for identifiers that consist of two or fewer letters.
Example:
Sysetm.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.
2.1.6.2Case 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 and POINT 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 and int 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 and Calculate are inappropriate method names because they differ only by case.
void calculate() void Calculate()
2.1.6.3Abbreviations
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.
Example:
Good: GetWindow Not Good: GetWin
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 and OLAP 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 of System.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.
2.1.6.4Namespace Naming Guidelines
You should use Pascal case for namespaces
T
CompanyName.TechnologyName[.Feature][.Design]
For example:
Microsoft.Media
Microsoft.Media.Design
he general rule for naming namespaces is to use the company name followed by the technology name and optionally the feature and design as follows.
2.1.6.5Class Naming Guidelines
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 name FileStream rather than CFileStream.
Do not use the underscore character (_).
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. Example : ApplicationException
public class FileStream public class Button public class String
Do not use the base word to access base class members unless you wish to resolve a conflict with subclasses member of the same name or when invoking base class constructors.
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 ) } }
2.1.6.6Interface Naming Guidelines
The following rules outline the naming guidelines for interfaces:
Name interfaces with nouns or noun phrases, or adjectives that describe behaviour.
Example:
IComponent // noun. ICustomAttributeProvider //noun. IPersistable //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 (_).
Always user Interfaces.
Example:
The following are examples of correctly named interfaces.
public interface IServiceProvider public interface IFormatable
The following code example illustrates how to define the interface IComponent and its standard implementation, the class Component.
public interface IComponent { // Implementation goes here. } public class Component: IComponent { // Implementation code goes here. }
Classes and interfaces should have at least 2:1 ratio of methods to properties.
Avoid interfaces with one method.
No more than 20 members per interface.
Avoid event as interface members.
Avoid abstract methods, user interfaces instead.
2.1.6.7Attribute Naming Guidelines
You should always add the suffix Attribute to custom attribute classes.
Example:
public class ObsoleteAttribute{}
2.1.6.8Enumeration Type Naming Guidelines
The enumeration (Enum) value type inherits from the Enum Class.
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.
Example:
Good: public enum Color { Red, Green, Blue } Not Good: Public enum Color { Red = 1, Green = 2, Blue = 3 } Specifying type for an enum Not Good: public enum Color : long { Red, Green, Blue }
2.1.6.9Static Field Naming Guidelines
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.
Example:
public static int Global1 = 100; public static int Global1 = 200;
2.1.6.10Parameter Naming Guidelines
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.
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.
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.
Do not prefix parameter names with Hungarian type notation.
Example: correctly named parameters
Type GetType(string typeName) string Format(string format, object[] args)
2.1.6.11Method Naming Guidelines
The following rules outline the naming guidelines for methods:
Use verbs or verb phrases to name methods.
Use Pascal case
Examples: Correctly named methods.
RemoveAll() GetCharArray() Invoke()
2.1.6.12Property Naming Guidelines
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.
Example:
Good: 1) public class smapleClass { public color BackColor { //Code for get and set assessors goes here. } } 2) Providing a property with the same name as a type. public enum Color { // Insert code for Enum here. } public class Control { public Color Color { get {// Insert code here.} set {// Insert code here.} } } Not Good: public enum Color { // Insert code for Enum here. } public class Control { public int Color { get {// Insert code here.} set {// Insert code here.} } } This is incorrect because the property Color is of type Integer.
2.1.6.13Event Naming Guidelines
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.
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, and DroppedDown.
Do not use a prefix or suffix on the event declaration on the type. For example, use Close instead of OnClose.
Example: Illustrates an event handler with an appropriate name and parameters.
public delegate void MouseEventHandler(object sender, MouseEventArgs e);
Example: Illustrates a correctly named event argument class.
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; } } }
2.1.6.14Delegate Naming Guidelines
The naming guidelines for events:
Use Pascal case.
Do not use Hungarian notation.
Copy a delegate to local variable before publishing to avoid concurrency race condition.
Always check a delegate for null before invoking it.
Use delegate inference instead of explicit delegate instantiation
delegate void SomeDegate(); public void SomeMethod() { //Code goes here. } SomeDelegate someDelegate = SomeMethod;
2.1.7Use Early Binding for Better performance
Early Binding provides much better performance than late binding.
Always specify a data type for variables when they are declared. This provides strong typing of variables for best performance.
Good: Early Binding String[] address = null; Not Good: Late Binding Object[] address = null;
2.1.8Returning Values
Try to make the structure of your program match the intent. Example:
if(booleanExpression) { return true; } else { return false; } should instead be written as return booleanExpression; Similarly, if(condition) { return x; } return y; should be written as return ((condition) ? x : y);
2.1.9Statements
2.1.9.1Simple Statements
argv++; /* Correct */ argc--; /* Correct */ argv++; argc--; /* AVOID! */
2.1.9.2Compound Statements
Compound statements are statements that contain lists of statements enclosed in braces
"{ statements }".
The enclosed statements should be indented one more level than the enclosing braces.
The opening brace should be at the beginning of the line that precedes the compound statement; the closing brace should begin a line and be indented to the opening brace.
Braces are used around all statements, even single statements, when they are part of a control structure, such as an if-else or for statement. This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces.
2.1.9.3if, if-else, if else-if else Statements
The if-else class of statements should have the following form:
if(condition) { statements; } if(condition) { statements; } else { statements; } if(condition) { statements; } else if(condition) { statements; } else { statements; }
Note: if statements always use braces {}. Avoid the following error-prone form:
if(condition) /* AVOID! THIS OMITS THE BRACES {}! */ statement;
2.1.9.4for Statements
A for statement should have the following form:
for(initialization; condition; update) { statements; }
An empty for statement (one in which all the work is done in the initialization, condition, and update clauses) should have the following form:
for(initialization; condition; update) { /* No Body */ }
When using the comma operator in the initialization or update clause of a "for" statement, avoid the complexity of using more than three variables.
If needed, use separate statements before the "for" loop (for the initialization clause) or at the end of the loop (for the update clause).
2.1.9.5while Statements
A while statement should have the following form:
while(condition) { statements; } An empty while statement should have the following form: while(condition) { /* No Body */ }
2.1.9.6do-while Statements
A do-while statement should have the following form:
do { statements; } while(condition);
2.1.9.7switch Statements
Never use goto unless in a switch statement fall through.
Always have a default case in a switch statement that asserts.
A switch statement should have the following form:
switch(condition) { case ABC: statements; /* falls through */ case DEF: statements; break; case XYZ: statements; break; default: statements; break; }
2.1.9.8Using Statement
Works with any IDisposable object
Data access classes, streams, text readers and writers, network classes, etc.
Good: using (Resource res = new Resource()) { res.DoWork(); } Not Good: Resource res = new Resource(...); try { res.DoWork(); } finally { if (res != null) ((IDisposable)res).Dispose(); }
Labels: C#