Easing logical OR and logical AND comparison in C#

How often have seen or written comparison code like this?

    public bool IsSupportedImage(string extension)
    {
        return (extension == "jpg" || extension == "jpeg" || extension == "png" || extension == "bmp");
    }

Every developer should answer with “yes” because logical OR and logical AND comparison is one of the basic concepts of programming. What I don´t “like” in this statement is the redundance of the parameter extension.

So I wrote some extension methods that I really use in every project at Tekaris.

    public static class ObjectExtensions
    {
        public static bool IsOneOf<T>(this T instance, params T[] these)
        {
            return these.Contains(instance);
        }

        public static bool IsOneOf<T>(this T instance, IEnumerable<T> these)
        {
            return !IsNoneOf(instance, these.ToArray());
        }

        public static bool IsNoneOf<T>(this T instance, params T[] these)
        {
            return !IsOneOf(instance, these);
        }

        public static bool IsNoneOf<T>(this T instance, IEnumerable<T> these)
        {
            return IsNoneOf(instance, these.ToArray());
        }
    }

The same comparison can be done this way:

    public bool IsSupportedImage(string extension)
    {
        return extension.IsOneOf("jpg", "jpeg", "png", "bmp");
    }

And a short example for IsNoneOf

    public static bool IsWeekday(string day)
    {
        return day.IsNoneOf("Saturday", "Sunday");
    }

Well it doesn´t make my day but it makes typing code slightly faster 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s