Enum with int value?

I want to do enumfor possible ratings. This is a working example:

public enum Grade
{
    A, B, C, D, E, F
}

However, I want the ratings to be integers, for example

public enum Grade
{
    1, 2, 3, 4, 5
}

Why does the first work, but not the second? How can I create a similar variable that can only take values ​​from 1-5 (and can be zero)?

+4
source share
5 answers
Items

enum must have valid C # identifiers; 1, 2, 3Etc. are not valid C # identifiers, so no: you cannot do this. You can use One = 1, etc., Or some common prefix ( Grade1), but ...

+9
source

Grade .

public enum Grade
{
    A = 1,
    B,
    C,
    D,
    E,
    F
}

B, C .. .

+9

# , enum , .. / , .

:

  • - .. Grade.One, Grade.Two ..
  • .

, , :

enum Grade {
    One = 1
,   Two
,   Three
,   Four
,   Five
}

, , :

enum Grade {
    _1 = 1 // Without =1 the value of _1 would be zero
,   _2
,   _3
,   _4
,   _5
}
+3

, , {1, 2, 3, etc}, , #.

, :

// Declare enum
public enum Grade
{
    A = 1,
    B,
    C,
    D,
    F
}

, say, Grade.B, :

int theIntGrade = (int)Grade.B  // after this line, theIntGrade will be equal to 2

, , "C", , :

Grade theLetterGrade = (Grade)Enum.Parse(typeof(Grade), "C", true); // final parameter sets case sensitivity for comparison
0

, 1-5 ( )?

:

public struct Grade: IEquatable<Grade>
{
    private int innerValue;
    private int InnerValue => isInitialized ? innerValue : 1;
    private readonly bool isInitialized;

    private Grade(int value)
    {
        if (value < 1 || value > 5)
            throw new OverflowException();

        innerValue = value;
        isInitialized = true;
    }

    public static implicit operator Grade(int i) => new Grade(i);
    public static explicit operator int(Grade g) =>  g.InnerValue;
    public override bool Equals(object obj) => obj is Grade && Equals((Grade)obj);
    public bool Equals(Grade other) => InnerValue == other.InnerValue;
    public override int GetHashCode() => InnerValue.GetHashCode();
    public override string ToString() => InnerValue.ToString();
    public static bool operator ==(Grade left, Grade right) => left.Equals(right);
    public static bool operator !=(Grade left, Grade right) => !left.Equals(right);
}

, 1, 2, 3, 4 5 - 1. , Grade g = 4;.

, ? : Grade? g = 4;.

0
source

Source: https://habr.com/ru/post/1673995/


All Articles