Aug 7, 2015

Get number of flags from an enum variable


Code:
public static class EnumHelper 
{
    public static UInt32 NumFlags(this Enum e)
    {
        UInt32 v = Convert.ToUInt32(e);
        v = v - ((v >> 1) & 0x55555555);
        v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
        UInt32 count = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
        return count;
    }
}

This is some kind of black magic, works very fast. Got here.

Lazy struct

Code:
    struct Lazy<T>
    {
        T value;
        bool init;
        Func<T> factory;

        public Lazy(Func<T> f)
        {
            factory = f;
            init = false;
            value = default(T);
        }

        public T Value
        {
            get
            {
                if (init) return value;
                else
                {
                    init = true;
                    return value = factory();
                }
            }
        }
    }


Variant with a single argument
is useful when we want to use a non-local function and don't want to use closure (for better performance)

Code:
    struct Lazy<TVal, TArg>
    {
        TVal value;
        TArg arg;
        bool init;
        Func<TArg, TVal> factory;

        public Lazy(Func<TArg, TVal> f, TArg arg)
        {
            factory = f;
            init = false;
            value = default(TVal);
            this.arg = arg;
        }

        public TVal Value
        {
            get
            {
                if (init) return value;
                else
                {
                    init = true;
                    return value = factory(arg);
                }
            }
        }
    }