DCSIMG
January 2010 - Posts - IronShay

January 2010 - Posts

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
Posted by shayf | 4 comment(s)
תגים:, ,

Vote to See IronRuby in MIX10

Do you want to hear about IronRuby in the upcoming MIX10 conference? If so, make sure to vote for my IronRuby session - IronRuby - the Development Booster Machine.

In the session I plan to talk a bit about the Ruby language and its strengths and then move on and show how .NET developers can take advantage of these stengths in several different scenarios like testing, debugging and Silverlight.

YOU have the power to make it happen! Go ahead and vote!
http://visitmix.com/opencallvote/Entry?entryId=IRONRU127

See you all there,
Shay.

Posted by shayf | with no comments

A New Year, A New Beginning

2010!

It’s a new year and the wind of change is in the air. This year is a big year for me – IronRuby Unleashed will be published (est. FEB 15th), another big project is coming (more details in a few weeks) and I changed jobs!

In the last 4 years I worked at a startup named ActionBase. I learned a lot at this place and managed to work with various platforms – Office addins, WinForms, Silverlight and ASP.NET. After 4 years it was a time for a change and I decided to move on. Starting from 1/1/2010 I’m a .NET technologies consultant and instructor at Sela. My main field is dynamic languages but I’ll be doing other stuff too. I’m really thrilled and excited to get started, help customers and spread my knowledge.

If you want me to come to your company to run a course or consult, don’t hesitate to contact me. This is my job now, not a hobby anymore, so go ahead and use me! :)

I wish you all a wonderful and happy new year. May this year will be the one you were waiting and hoping for!

Peace and love,
Shay.

Posted by shayf | 1 comment(s)
תגים: