This blog has, IMO, some great resources. Unfortunately, some of those resources are becoming less relevant. I'm still blogging, learning tech and helping others...please find me at my new home on http://www.jameschambers.com/.

Thursday, March 3, 2011

Extension Methods for Converting ints and bools

I was recently working on a chunk of code where I had three different scenarios for conversion.  With two external libraries (something I couldn’t change) and this not being a big enough project (so not worth a facade) as driving factors I rolled a couple of simple to use extension methods.

The Code

I won’t lollygag here too much.  You need a namespace and static class name that work for your (they’re more-or-less irrelevant in the grander scheme), and a couple of static methods.

namespace ExtensionMethods
{
    public static class Extensions
    {
        public static bool ToBool(this int i)
        {
            return i == 0 ? false : true;
        }

        public static int ToInt(this bool b)
        {
            return b ? 1 : 0;
        }

        public static int ToInt(this bool? b)
        {
            return b.HasValue ? (b.Value ? 1 : 0) : 0;
        }
    }
}

Basically, we’re just using a tertiary operation to decide which value is appropriate to use in each of the contexts.

The third method is there to help out with nullable boolean values.  This was handy in my case, not sure how many people would need this.

No comments:

Post a Comment