5

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.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
pennyrave
  • 750
  • 2
  • 18
  • 32

2 Answers2

3

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;   
}   
John Saunders
  • 160,644
  • 26
  • 247
  • 397
  • True - I would add that it would be better to have a Disk class with methods that holds a flags enum of DiskFormat. Disk could have other useful methods (like length, etc.) – Geoff Cox May 19 '12 at 02:11
  • Ahh.. well, design was that it was just a simple tracking of what kind of DVD disc it was, DVD, Bul-ray, Blu-ray 3D, digital copy, etc. It was not going to be added onto beyond that. I am not modifying anything, so a static type enum worked well. Thank you, though. – pennyrave May 19 '12 at 04:14
2

As of C# 7.2

Just add ref

internal static void AddFormat(ref this Movie.eDiskFormat target, Movie.eDiskFormat newFormat)
{
    target |= newFormat;
}
Knight0fDragon
  • 16,609
  • 2
  • 23
  • 44