Search code examples
c#enumsextension-methods

Extension Method to modify an enum value


I'm a little new to extensions. I looked around for an existing answer before posting this as I hate to write, but I didn't see anything that I found helpful.

I want to have an extension method for an enum with the Flag attribute that I can call to basically append another enum/flag to the calling enum.

Before someone downvotes this into Int32.MinValue, I did look a fair amount, but all I found was a bunch of questions for "IsFlagSo-and-SoSet" and processing on flags, but not the simple adding of a flag.

I defined the enum as the following:

    [Flags]
    internal enum eDiskFormat
    {
        None        = 0x00,

        _3D         = 0x01,

        Blu_ray_3D  = 0x02,

        Blu_ray     = 0x04,

        DigitalCopy = 0x08,

        Dvd         = 0x10

    }

The extension was defined as:

    internal static void AddFormat(this Movie.eDiskFormat target, Movie.eDiskFormat newFormat)
    {
        target |= newFormat;
    }

When I called it as the following, I expected the resulting enum to be Movie.eDiskFormat.Blu_ray... (It was initialized as eDiskFormat.None).

m.DiskFormat.AddFormat(Movie.eDiskFormat.Blu_ray);

Instead, the resulting value is still eDiskFormat.None. I thought that the passing of the variable with "this" was the very similar as passing by reference, but I am obviously incorrect. The value inside the method is as I thought, but the result... well, I suppose I stated that already; thus this question.


Solution

  • Enums are value types. They are immutable. You cannot change their value.

    The best you could do is something like this:

    m.DiskFormat = m.DiskFormat.AddFormat(Movie.eDiskFormat.Blu_ray); 
    

    Where

    internal static Movie.eDiskFormat AddFormat(this Movie.eDiskFormat target, 
                                                     Movie.eDiskFormat newFormat)   
    {   
        return target | newFormat;   
    }