Thursday, October 30, 2014

Clean code in C# Part 1

12:10 AM - By azeheruddin khan 0

This is my first post for clean code. I always try to keep my code simple. Here i will show you both old and new fashioned of writing a code. Before proceeding further to code ,you should know why should we care about clean code.

Why should you or I care ?
  1. Easier to read.
  2. Quicker to write.
  3. Easier to test.
  4. Increase the performance.

Old Fashioned Code


string[] strArray = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };

public string GetCommaSeparatedValues()
{
    var stringBuilderResult = new StringBuilder();
    var blnFirst = true;
    foreach (var strNumber in strArray)
    {
        if (!blnFirst) stringBuilderResult.Append(',');
        else blnFirst = false;
        stringBuilderResult.Append("'" + strNumber + "'");
    }
    return stringBuilderResult.ToString();
}


New Fashioned Code


string[] strArray = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };

public string GetCommaSeparatedValues_Updated()
{
    return string.Join(",",strArray.Select(s => "'" +s+ "'"));
}


Final Output


'1','2','3','4','5','6','7','8','9' 

Tags:
About the Author

I am Azeheruddin Khan having more than 6 year experience in c#, Asp.net and ms sql.My work comprise of medium and enterprise level projects using asp.net and other Microsoft .net technologies. Please feel free to contact me for any queries via posting comments on my blog,i will try to reply as early as possible. Follow me @fresher2programmer
View all posts by admin →

Get Updates

Subscribe to our e-mail newsletter to receive updates.

Share This Post

0 comments:

adsense

© 2014 Fresher2Programmer. WP Theme-junkie converted by Bloggertheme9
Powered by Blogger.
back to top