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?
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.)
You could try something like
FileOverwriteMode overwriteMode = FileOverwriteMode.DateAndSize;
if (new HashSet<FileOverwriteMode>
{
FileOverwriteMode.DateAndSize,
FileOverwriteMode.DateOrSize,
FileOverwriteMode.Date,
FileOverwriteMode.Size
}.Contains(overwriteMode))
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With