C# プログラムの一般構造

C# プログラムは、1 つ以上のファイルで構成されます。 各ファイルには、0 個以上の名前空間が含まれます。 名前空間には、クラス、構造体、インターフェイス、列挙型、およびデリゲートなどの型、または別の名前空間が含まれます。 次に示す例は、これらの要素をすべて含む C# プログラムのスケルトンです。

// A skeleton of a C# program
using System;

// Your program starts here:
Console.WriteLine("Hello world!");

namespace YourNamespace
{
    class YourClass
    {
    }

    struct YourStruct
    {
    }

    interface IYourInterface
    {
    }

    delegate int YourDelegate();

    enum YourEnum
    {
    }

    namespace YourNestedNamespace
    {
        struct YourStruct
        {
        }
    }
}

前の例では、プログラムのエントリ ポイントに "最上位レベルのステートメント" が使用されています。 この機能は、C# 9 で追加されました。 C# 9 より前では、次の例に示すように、エントリ ポイントは Main という名前の静的メソッドでした。

// A skeleton of a C# program
using System;
namespace YourNamespace
{
    class YourClass
    {
    }

    struct YourStruct
    {
    }

    interface IYourInterface
    {
    }

    delegate int YourDelegate();

    enum YourEnum
    {
    }

    namespace YourNestedNamespace
    {
        struct YourStruct
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //Your program starts here...
            Console.WriteLine("Hello world!");
        }
    }
}

これらのプログラム要素については、基礎に関するガイドのについてのセクションで説明します。

C# 言語仕様

詳細については、「C# 言語の仕様」の「基本概念」を参照してください。 言語仕様は、C# の構文と使用法に関する信頼性のある情報源です。