DCSIMG
Use .NET Built-in Methods to Save Time and Headaches - IronShay

Use .NET Built-in Methods to Save Time and Headaches

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!
}

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

  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;  

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).

All the best,
Shay.

kick it on DotNetKicks.com Shout it
Published Saturday, January 16, 2010 7:14 PM by shayf
תגים:, ,

Comments

# re: Use .NET Built-in Methods to Save Time and Headaches

Really nice, it is always funny to see that most of the people don't know all these blocks (especially the path combine functinos)

J.

Saturday, January 16, 2010 9:31 PM by Josh

# re: Use .NET Built-in Methods to Save Time and Headaches

Here's my take - Writing a string to a file:

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);

If you publish it please also link to my blog (webservices20.blogspot.com).

Saturday, January 16, 2010 10:15 PM by Yaron Naveh

# re: Use .NET Built-in Methods to Save Time and Headaches

Confused?

In codeblock #9, what do you think the value of Sample.A is?

Saturday, January 16, 2010 10:47 PM by Kim

# re: Use .NET Built-in Methods to Save Time and Headaches

Thank you for this list. I readed it and updated some lines on my code. :)

Tuesday, April 06, 2010 4:46 AM by Tony

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: