Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I convert this Delphi Set code to C#?

Tags:

c#

set

delphi

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?

like image 578
Pauk Avatar asked Feb 22 '10 11:02

Pauk


2 Answers

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.)

like image 132
Jon Skeet Avatar answered Sep 28 '22 00:09

Jon Skeet


You could try something like

FileOverwriteMode overwriteMode = FileOverwriteMode.DateAndSize;
if (new HashSet<FileOverwriteMode> 
    { 
        FileOverwriteMode.DateAndSize, 
        FileOverwriteMode.DateOrSize, 
        FileOverwriteMode.Date, 
        FileOverwriteMode.Size 
    }.Contains(overwriteMode))
{
}
like image 26
Adriaan Stander Avatar answered Sep 28 '22 00:09

Adriaan Stander