Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set In enum for C#

Tags:

c#

c#-3.0

I would like to find a way to check to see if a set of values are contained in my variable.

[Flags]
public enum Combinations
{
    Type1CategoryA = 0x01,      // 00000001
    Type1CategoryB = 0x02,      // 00000010
    Type1CategoryC = 0x04,      // 00000100
    Type2CategoryA = 0x08,      // 00001000
    Type2CategoryB = 0x10,      // 00010000
    Type2CategoryC = 0x20,      // 00100000
    Type3 = 0x40                // 01000000
}

bool CheckForCategoryB(byte combinations)
{

    // This is where I am making up syntax

    if (combinations in [Combinations.Type1CategoryB, Combinations.Type2CategoryB])
        return true;
    return false;

    // End made up syntax
}

I am a transplant to .NET from Delphi. This is fairly easy code to write in Delphi, but I am not sure how to do it in C#.

like image 411
Vaccano Avatar asked Dec 21 '09 20:12

Vaccano


People also ask

Can we assign value to enum in C?

An enum is considered an integer type. So you can assign an integer to a variable with an enum type.

What is the type of enum in C?

In C programming, an enumeration type (also called enum) is a data type that consists of integral constants. To define enums, the enum keyword is used. enum flag {const1, const2, ..., constN}; By default, const1 is 0, const2 is 1 and so on.

How do you assign an enum?

Enum ValuesA change in the default value of an enum member will automatically assign incremental values to the other members sequentially. You can even assign different values to each member. The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong.

Is enum a data type in C?

Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.


1 Answers

If you mean "at least one of the flags":

return (combinations
     & (byte)( Combinations.Type1CategoryB | Combinations.Type2CategoryB)) != 0;

also - if you declare it as Combinations combinations (rather than byte), you can drop the (byte)

bool CheckForCategoryC(Combinations combinations)
{
    return (combinations & (Combinations.Type1CategoryB | Combinations.Type2CategoryB) ) != 0;
}

If you mean "exactly one of", I would just use a switch or if etc.

like image 154
Marc Gravell Avatar answered Sep 21 '22 17:09

Marc Gravell