July 16, 2010

FileAttributesExtender

Use Flags based enumerated types extender class to extend file attributes and give it Set/group theory like methods
public static class FileAttributesExtender
{
    // Return lhs flags plus rhs flags
    public static FileAttributes Union(this FileAttributes lhs, FileAttributes rhs)
    {
        return lhs | rhs;
    }

    // Return flags common to lhs and rhs
    public static FileAttributes Intersection(this FileAttributes lhs, FileAttributes rhs)
    {
        return lhs & rhs;
    }

    // Return lhs flags minus rhs flags
    public static FileAttributes Difference(this FileAttributes lhs, FileAttributes rhs)
    {
        FileAttributes common = Intersection(lhs, rhs);
        int res = (int)lhs - (int)common;
        return (FileAttributes)(res);
    }

    // Return true if lhs contains ALL the flags within rhs
    public static bool Contains(this FileAttributes lhs, FileAttributes rhs)
    {
        FileAttributes common = Intersection(lhs, rhs);
        return (common == rhs);
    }

    // Return true if lhs contains any of the flags within rhs
    public static bool ContainsAnyOf(this FileAttributes lhs, FileAttributes rhs)
    {
        FileAttributes common = Intersection(lhs, rhs);
        return ((int)common > 0);
    }

    // Return true if lhs contains none of the flags within rhs
    public static bool ContainsNoneOf(this FileAttributes lhs, FileAttributes rhs)
    {
        FileAttributes common = Intersection(lhs, rhs);
        return ((int)common == 0);
    }

    // NON-extension methods here
    public static FileAttributes FromString(string source)
    {
        FileAttributes res = (FileAttributes)Enum.Parse(typeof(FileAttributes), source, true);
        return res;
    }

}

No comments: