During our everyday programming tasks we run into several repetitive code blocks that after the 20th time you implement them become really annoying. The worst case is to re-implement these code blocks every time, and the better case is to create a central class library with helper classes and methods. However, a large amount of these tasks can be achieved easily with built-in .NET methods.

In this post I will go through several repetitive code blocks and show you how to implement them using built-in .NET method. If you want to add your suggestions, comment! I’ll add your suggestions to the post periodically.

Disclaimer: I’m sure some of the code blocks I use in the NOT Recommended sections can be written much better. These code blocks are here just for demonstration purposes.

Code Block #1 – Check string for nullity or emptiness

NOT Recommended

  1. str = "something"  
  2. if (str == null || str == String.Empty)  
  3. {  
  4.     // Oh no! the string isn't valid!  
  5. }  

Recommended

  1. str = "something"  
  2. if (String.IsNullOrEmpty(str))  
  3. {  
  4.     // Oh no! the string isn't valid!  
  5. }  

Code Block #2 – Check string for nullity or emptiness (spaces only string is invalid too)

NOT Recommended

  1. str = "something"  
  2. if (str == null || str.Trim() == String.Empty)  
  3. {  
  4.     // Oh no! the string isn't valid!  
  5. }  

Recommended (C# 4.0 Only)

  1. str = "something"  
  2. if (String.IsNullOrWhiteSpace(str))  
  3. {  
  4.     // Oh no! the string isn't valid!  
  5. }  

Code Block #3 – Copy an Array

NOT Recommended

  1. string[] source = new string[] { "a""b""c" };  
  2. string[] dest = new string[3];  
  3. for (int i=0; i < source.Length; i++)  
  4. {  
  5.     dest[i] = source[i];  
  6. }  

Recommended

  1. string[] source = new string[] { "a""b""c" };  
  2. string[] dest = new string[3];  
  3. Array.Copy(surce, dest, source.Length);  

Code Block #4 – Check if a char is a digit

NOT Recommended

  1. char c = '1';  
  2. if (c == '1' || c == '2' || c == '3' ||  
  3.     c == '4' || c == '5' || c == '6' ||  
  4.     c == '7' || c == '8' || c == '9' ||  
  5.     c == '0')  
  6. {  
  7.     // It's a digit!  
  8. }  

Recommended

  1. char c = '1';  
  2. if (Char.IsDigit(c))  
  3. {  
  4.     // It's a digit!  
  5. }  

Code Block #5 – Combine Paths

NOT Recommended

  1. string folder = @"C:\MyDir";  
  2. string file = "MyFile.docx";  
  3. // Combine to make a path  
  4. string path = folder + @"\" + file;  

Recommended

  1. string folder = @"C:\MyDir";  
  2. string file = "MyFile.docx";  
  3. // Combine  
  4. string path = System.IO.Path.Combine(folder, file);  

Code Block #6 – Get file extension out of a file path

NOT Recommended

  1. string path = @"C:\MyDir\MyFile.docx";  
  2. string extension = path.Substring(path.LastIndexOf("."));  

Recommended

  1. string path = @"C:\MyDir\MyFile.docx";  
  2. string extension = System.IO.Path.GetExtension(path);  

Code Block #7 – Get MyDocuments Path

NOT Recommended

  1. // Probably some nasty stuff here  

Recommended

  1. Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);  

Code Block #8 – Check if object is of a specific type

NOT Recommended

  1. object obj = "str";  
  2. if (obj.GetType() == typeof(String))  
  3. {  
  4.     // It's a string!  
  5. }  

Recommended

  1. object obj = "str";  
  2. if (obj is String)  
  3. {  
  4.     // It's a string!  
  5. }  

As Adrian Aisemberg has pointed out, these samples are not entirely the same. The is keyword will return true also if obj is of a derivative type of String (in this sample).

Code Block #9 – Set default enum value

NOT Recommended

  1. public class MyClass  
  2. {  
  3.     private enum Sample   
  4.     {  
  5.         A,  
  6.         B,  
  7.         C  
  8.     }  
  9.     static Sample s = Sample.B; // Set default value explicitly  
  10.     public static void Run()  
  11.     {     
  12.         Console.WriteLine(s); // Prints B  
  13.     }  
  14. }  

Recommended

  1. public class MyClass  
  2. {  
  3.     private enum Sample   
  4.     {  
  5.         A,  
  6.         B = 0, // Make B the default value  
  7.         C  
  8.     }  
  9.     static Sample s; // Default value will be used  
  10.     public static void Run()  
  11.     {     
  12.         Console.WriteLine(s); // Prints B  
  13.     }  
  14. }  

Code Block #10 – Check if a string starts with another string

NOT Recommended

  1. string str = "Hello World";  
  2. if (str.Substring(0, 5) == "Hello")  
  3. {  
  4.     // String starts with Hello!              
  5. }  

Recommended

  1. string str = "Hello World";  
  2. if (str.StartsWith("Hello"))  
  3. {  
  4.     // String starts with Hello!          
  5. }  

Code Block #11 – Convert list of items of one type to a list of items of a different type

NOT Recommended

  1. List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });  
  2. List<string> convertedList = new List<string>();  
  3. foreach (int item in list)  
  4. {  
  5.     convertedList.Add(item.ToString());  
  6. }  

Recommended

  1. List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });  
  2. List<string> convertedList = list.ConvertAll<string>(Convert.ToString);  

Code Block #12 – Check if a string contains a number and get the number

NOT Recommended

  1. string str = "4";  
  2.   
  3. int num = 0;  
  4. bool success = false;  
  5. try   
  6. {  
  7.     num = Convert.ToInt32(str);  
  8.     success = true;  
  9. }  
  10. catch  
  11. {  
  12.     success = false;  
  13. }  
  14.   
  15. if (success)  
  16. {  
  17.     // Do something with the number  
  18. }  

Recommended

  1. string str = "4";  
  2.   
  3. int num = 0;  
  4. if (Int32.TryParse(str, out num))  
  5. {  
  6.     // Do something with the number  
  7. }  

Code Block #13 – Writing a string to a file (courtesy of Yaron Naveh)

NOT Recommended

  1. const string str = "put me in a file";  
  2. const string file = @"c:\logs\file.txt";  
  3.   
  4. var fs = new FileStream(file, FileMode.Create);            
  5. var sw = new StreamWriter(fs);  
  6. sw.Write(str);  
  7.   
  8. sw.Close();  
  9. fs.Close();  

Recommended

  1. const string str = "put me in a file";  
  2. const string file = @"c:\logs\file.txt";  
  3.   
  4. File.WriteAllText(file, str);  

Code Block #14 – Pick value if not null and a different on if it is (courtesy of Abhishek)

NOT Recommended

  1. string input = "sdfds";  
  2. string result = null;  
  3. if (input == null)  
  4. {  
  5.     result = "Input is null!";  
  6. }  
  7. else  
  8. {  
  9.     result = input;  
  10. }  

Recommended

  1. string input = "sdfds";  
  2. string result = input ?? "Input is null!";  

 

This is it for now. If you have more, comment and I’ll add your suggestions to the list (with credits).

Posted via email from fenildesai's posterous