c# enums

  • enum is a value type, i.e. they are created on the stack
  • Default enum type is int.
    for example
    enum Test(yes,no);
    will create a int enum list
  • The value assigned to a instance of the enum is not limited to the named contants
    for example
    enum Test:int {t=9,y=8};
    Test t = (Test)10;
    System.Console.Writeln(t);
    will not throw any error and will print 10
  • enum Test:int{t=9};
    System.Console.Writeln(Test.t);
    What will be the output of the above snippet?
    will it be “9” or “t”
  • enum Test:int { t=19, y=18 };
    int i = Test.t;
    Console.Write(i);
    What will be the output of the above program?
  • Difference between enum and a constant
    enum is strongly types than contant
    For example

    the function
    int PrintNoOfDays(int month)
    can be called as
    const int Jan = 1;
    const int Feb = 2; ….
    PrintNoOfDays(Jan);

    or the function can be declared as
     can be called as
    enum Month {Jan,Feb,….)
    int PrintNoOfDays(Month m)

    PrintNoOfDays(Month.Jan)

    The second example is strongly typed

  • Enum under the covers
    When compiling an enum it is converted to struct enum Month {Jan,Feb,….)
    the above enum of months would be converted to
    struct Month : System.Enum
    {
    public const int Jan = 1;
    public const int Feb = 2;

    }
  • The following code will not give any error (there is a comma after the last enum list constant)public enum Test
    {
    a = 1,
    b = 0,

    }

  • What will be the output of
    System.Console.WriteLine(sizeof(Test));
  • Advertisements

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s


    %d bloggers like this: