Week ago i started a series of blog posts about coding standards and best practices and i will be posting those post between my personal and Integrant blogs, as one of the most things i love about Integrant is that all the developers are concerned about using coding standards and best practices and approaches,
As best practices and coding standards works like a contract between the developers to ensure maintainability, readability, performance and usability, for example I’m writing a piece of code in a certain module and for whatever reason I will not be able to continue coding in that nodule, and another developer need to do some changes in the code due some changes in customer requests, do if this code being wrote with coding standards, the other developer will be easily able to read it, and using best practices for sure will help that developer to maintain this code easily, and even can reuse it in another module, Most of developers can write “Working Code” but not “Efficient Code”.
and this time a common issue i have faced working with Mid-Level and Junior developers is dealing with strings, like the following example
1 string userName = "Peter Bahaa";
2 string message = "Hi Mr. ( " + userName + ")";
The issue is that adding + operator after the “Hi Mr.” string initializing another object in the memory, Perhaps concatenating two string with plus format will not affect your application performance, but imaging that each time you want to concatenate two string together - for any purpose (special formatting , display a specific message) – by adding a plus will create another object in the memory , and simply by using String.Format that will enhance your application performance, so there are a great function called String.Format this function is simply doing formatting and decoration for your string, and also you can set the culture for this formatting so you can use it when in multi language application development. for example
1 string message = String.Format(CultureInfo.CurrentCulture, "Hi {0} {1}; your birthday is: {2:MMMM dd yyyy} and you won {3:C3}", title, userName, birthdate, prize);
So using String.Format will ease the job and will grantee no more object creation in the memory For more info about String.Format see the following link http://blog.stevex.net/string-formatting-in-csharp/
One more thing about dealing with strings is when we just want to concatenate two or more string or a hug number of strings
for small number of strings you can use String.Concat and never use the + operator to concatenate strings
1 String.Concat("Peter", " ", "Bahaa")
and for large amount of strings always use StringBuilder Class
1 StringBuilder builder = new StringBuilder();
2 builder.Append("Message \n\r");
3 builder.AppendFormat(CultureInfo.CurrentCulture, "Hi {0} {1}; your birthday is: {2:MMMM dd yyyy} and you won {3:C3}", title, userName, birthdate, prize);
4 Console.Write(builder.ToString());
I hope this helps :) , Have a nice day every one.