views:

270

answers:

3

I've got the following Delphi code that defines a set and then a simple if statement that checks if a passed value of the set type falls within certain values.

TOverwriteMode = (omNone, omDateAndSize, omDateOrSize, omDate, omSize, omForce);

...

if OverwriteMode in [omDateAndSize, omDateOrSize, omDate, omSize] then
begin
end;

I've converted it to C# using an enum, but the code for checking the value now consists of an if or statement which seems a bit long winded to me.

public enum FileOverwriteMode
{
    None,
    DateAndSize,
    DateOrSize,
    Date,
    Size,
    Force,
}

...

if ((overwriteMode == FileOverwriteMode.DateAndSize) || 
    (overwriteMode == FileOverwriteMode.DateOrSize) || 
    (overwriteMode == FileOverwriteMode.Date) || 
    (overwriteMode == FileOverwriteMode.Size))
{
}

Is there a way to simplify it using some kind of C# set equivalent?

+2  A: 

You could try something like

FileOverwriteMode overwriteMode = FileOverwriteMode.DateAndSize;
if (new HashSet<FileOverwriteMode> 
    { 
        FileOverwriteMode.DateAndSize, 
        FileOverwriteMode.DateOrSize, 
        FileOverwriteMode.Date, 
        FileOverwriteMode.Size 
    }.Contains(overwriteMode))
{
}
astander
I thought it would be HashSet, but wasn't sure how to go about it. I like the inline creation, but John's answer just sneaks it for me since it will be checked upon a lot, so having it already created helps.
Pauk
+8  A: 

Well, you can do:

private static readonly HashSet<FileOverWriteMode> ValidOverwriteModes
    = new HashSet<FileOverWriteMode>
{
    FileOverwriteMode.DateAndSize, FileOverwriteMode.DateOrSize,
    FileOverwriteMode.Date, FileOverwriteMode.Size,
};

...

if (ValidOverwriteModes.Contains(overwriteMode))
{
    // ...
}

(Rename ValidOverwriteModes depending on what the real meaning is.)

Jon Skeet
Thanks Jon, that works nicely. I just needed to add HashSet<FileOverwriteMode> after the readonly to make it compile and it was good to go! (Apologies for the name typo!)
Pauk
@Pauk: Doh - that was due to having `var` there before :) Will edit it into the answer.
Jon Skeet
+6  A: 

Jon's HashSet solution looks cleaner but here is one of the lightweight solutions:

[Flags]
public enum FileOverwriteMode
{
    None = 1,
    DateAndSize = 2,
    DateOrSize = 4,
    Date = 8,
    Size = 16,
    Force = 32,
}

and check it like:

// you might need to do some typecasting here and there
const int desiredMode = FileOverwriteMode.DateAndSize 
    | FileOverwriteMode.DateOrSize 
    | FileOverwriteMode.Size;

if(overwriteMode & desiredMode == desiredMode) 
{
}
ssg
It might have the an upper limit in the magnitude of 2log(max size of enum), while Delphi sets allow 256 items max. The hash set solution isthen better
Marco van de Voort
@Marco: That's right. We're probably limited to 31-32 items max here. However it seemed reasonable enough for asker's scenario.
ssg