Method extension for safely type convert
- by outcoldman
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)