Method extension for safely type convert

Recently I read good Russian post with many interesting extensions methods after then I remembered that I too have one good extension method “Safely type convert”. Idea of this method I got at last job.

We often write code like this:

int intValue;

if (obj == null || !int.TryParse(obj.ToString(), out intValue))

    intValue = 0;

 

This is method how to safely parse object to int. Of course will be good if we will create some unify method for safely casting.

I found that better way is to create extension methods and use them then follows:

int i;

i = "1".To<int>();

// i == 1

i = "1a".To<int>();

// i == 0 (default value of int)

i = "1a".To(10);

// i == 10 (set as default value 10)

i = "1".To(10);

// i == 1

// ********** Nullable sample **************

int? j;

j = "1".To<int?>();

// j == 1

j = "1a".To<int?>();

// j == null

j = "1a".To<int?>(10);

// j == 10

j = "1".To<int?>(10);

// j == 1


Read more… (redirect to http://outcoldman.ru)

Regular Expressions. Remember it, write it, test it.

I should say that I’m fan of regular expressions. Whenever I see the problem, which I can solve with Regex, I felt a burning desire to do it and going to write new test for new regex. Previously I had installed SharpDevelop Studio just for good regular expression tool in it (Why VS doesn’t have one?). But now I’m a little wiser, and for each Regex I write a separate test.


I find it difficult to remember the syntax of regular expressions (I don’t write them very often); I always forget which character is responsible for the beginning of the line, etc. So I use external small and easy articles like this “Regular expressions – An introduction”.


Now I want to show you little samples of regular expressions and want to show you how to test these samples.


Read more… (redirect to http://outcoldman.ru)