Method extension for safely type convert

Posted by outcoldman on ASP.net Weblogs See other posts from ASP.net Weblogs or by outcoldman
Published on Thu, 25 Mar 2010 21:01:00 GMT Indexed on 2010/03/25 21:13 UTC
Read the original article Hit count: 857

Filed under:
|
|
|
|

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)

© ASP.net Weblogs or respective owner

Related posts about c#

Related posts about .NET