Type definitions in top-level statements

Type definitions in top-level statements#

C# does not allow types definitions in the top if we use top-level statements. Types must be moved towards the end of our code:

enum not allowed as follows:
internal enum Color
{
    Red,
    Yellow,
    Green
}

Color agent = Color.Red, human = Color.Green;

Console.WriteLine($"agent: {agent}");
Console.WriteLine($"human: {human}");
✅ Ok:
Color agent = Color.Red, human = Color.Green;

Console.WriteLine($"agent: {agent}");
Console.WriteLine($"human: {human}");

internal enum Color
{
    Red,
    Yellow,
    Green
}

This is probably because:

  • types cannot be nested in methods

  • the compiler requires a clear separation between Main code and other code.

The compiler wraps top-level statements as follows:

namespace ConsoleApp1;

internal class Program
{
    private static void Main(string[] args)
    {
        Color agent = Color.Red, human = Color.Green;

        Console.WriteLine($"agent: {agent}");
        Console.WriteLine($"human: {human}");
    }
}

internal enum Color
{
    Red,
    Yellow,
    Green
}