Search code examples
c#enumscoding-style

Define enums within a method in C#?


I have mainly a C++ background and I am learning C#. So, I need some help with C# idioms and style.

I am trying to write, in C#, a small text-file parsing method in which I need a simple state variable with three states. In C++ I would declare an enum like this for the state variable:

enum { stHeader, stBody, stFooter} state = stBody;

...and then use it in my parsing loop like this:

if (state == stHeader && input == ".endheader")
{
  state = stBody;
}

In C# I realize that it is not possible to declare an enum inside a method. So, what I am supposed to do for sake of clean style? Declare this internal enum outside of the method? Use magic numbers 1,2,3? Create a separate class for this?

Please help me clear up my confusion.


Solution

  • The closest you can get is a private nested enum with in the class:

    public class TheClass
    {
        private enum TheEnum 
        {
           stHeader, 
           stBody, 
           stFooter
        }
    
        // ...the rest of the methods properties etc... 
    }