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".ToRealization of this approach:
``` public static class Parser { ///This realization isn’t full – this is small method part, I use it at my site engine. It can work with int, long, bool, string, enums (with Nullable type of this types too). I think that you can add types very easy for this method (don’t forget about culture).
Obviously this approach you can use just inside of developers group, because It is not obviously why this method can’t cast any type A to type B.