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
- str = "something"
- if (str == null || str == String.Empty)
- {
- // Oh no! the string isn't valid!
- }
Recommended
- str = "something"
- if (String.IsNullOrEmpty(str))
- {
- // Oh no! the string isn't valid!
- }
Code Block #2 – Check string for nullity or emptiness (spaces only string is invalid too)
NOT Recommended
- str = "something"
- if (str == null || str.Trim() == String.Empty)
- {
- // Oh no! the string isn't valid!
- }
Recommended (C# 4.0 Only)
- str = "something"
- if (String.IsNullOrWhiteSpace(str))
- {
- // Oh no! the string isn't valid!
- }
Code Block #3 – Copy an Array
NOT Recommended
- string[] source = new string[] { "a", "b", "c" };
- string[] dest = new string[3];
- for (int i=0; i < source.Length; i++)
- {
- dest[i] = source[i];
- }
Recommended
- string[] source = new string[] { "a", "b", "c" };
- string[] dest = new string[3];
- Array.Copy(surce, dest, source.Length);
Code Block #4 – Check if a char is a digit
NOT Recommended
- char c = '1';
- if (c == '1' || c == '2' || c == '3' ||
- c == '4' || c == '5' || c == '6' ||
- c == '7' || c == '8' || c == '9' ||
- c == '0')
- {
- // It's a digit!
- }
Recommended
- char c = '1';
- if (Char.IsDigit(c))
- {
- // It's a digit!
- }
Code Block #5 – Combine Paths
NOT Recommended
- string folder = @"C:\MyDir";
- string file = "MyFile.docx";
- // Combine to make a path
- string path = folder + @"\" + file;
Recommended
- string folder = @"C:\MyDir";
- string file = "MyFile.docx";
- // Combine
- string path = System.IO.Path.Combine(folder, file);
Code Block #6 – Get file extension out of a file path
NOT Recommended
- string path = @"C:\MyDir\MyFile.docx";
- string extension = path.Substring(path.LastIndexOf("."));
Recommended
- string path = @"C:\MyDir\MyFile.docx";
- string extension = System.IO.Path.GetExtension(path);
Code Block #7 – Get MyDocuments Path
NOT Recommended
- // Probably some nasty stuff here
Recommended
- Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Code Block #8 – Check if object is of a specific type
NOT Recommended
- object obj = "str";
- if (obj.GetType() == typeof(String))
- {
- // It's a string!
- }
Recommended
- object obj = "str";
- if (obj is String)
- {
- // It's a string!
- }
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
- public class MyClass
- {
- private enum Sample
- {
- A,
- B,
- C
- }
- static Sample s = Sample.B; // Set default value explicitly
- public static void Run()
- {
- Console.WriteLine(s); // Prints B
- }
- }
Recommended
- public class MyClass
- {
- private enum Sample
- {
- A,
- B = 0, // Make B the default value
- C
- }
- static Sample s; // Default value will be used
- public static void Run()
- {
- Console.WriteLine(s); // Prints B
- }
- }
Code Block #10 – Check if a string starts with another string
NOT Recommended
- string str = "Hello World";
- if (str.Substring(0, 5) == "Hello")
- {
- // String starts with Hello!
- }
Recommended
- string str = "Hello World";
- if (str.StartsWith("Hello"))
- {
- // String starts with Hello!
- }
Code Block #11 – Convert list of items of one type to a list of items of a different type
NOT Recommended
- List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });
- List<string> convertedList = new List<string>();
- foreach (int item in list)
- {
- convertedList.Add(item.ToString());
- }
Recommended
- List<int> list = new List<int>(new[] { 1, 2, 3, 4, 5 });
- List<string> convertedList = list.ConvertAll<string>(Convert.ToString);
Code Block #12 – Check if a string contains a number and get the number
NOT Recommended
- string str = "4";
- int num = 0;
- bool success = false;
- try
- {
- num = Convert.ToInt32(str);
- success = true;
- }
- catch
- {
- success = false;
- }
- if (success)
- {
- // Do something with the number
- }
Recommended
- string str = "4";
- int num = 0;
- if (Int32.TryParse(str, out num))
- {
- // Do something with the number
- }
Code Block #13 – Writing a string to a file (courtesy of Yaron Naveh)
NOT Recommended
- const string str = "put me in a file";
- const string file = @"c:\logs\file.txt";
- var fs = new FileStream(file, FileMode.Create);
- var sw = new StreamWriter(fs);
- sw.Write(str);
- sw.Close();
- fs.Close();
Recommended
- const string str = "put me in a file";
- const string file = @"c:\logs\file.txt";
- File.WriteAllText(file, str);
Code Block #14 – Pick value if not null and a different on if it is (courtesy of Abhishek)
NOT Recommended
- string input = "sdfds";
- string result = null;
- if (input == null)
- {
- result = "Input is null!";
- }
- else
- {
- result = input;
- }
Recommended
- string input = "sdfds";
- 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).
0 Please Share a Your Opinion.: