1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#の namespace(名前空間)とは

Posted at

C#の namespace(名前空間) は、簡単に言うと クラスやメソッドの「住所」や「フォルダ」 のようなものです。

1. なぜnamespaceが必要か?

プログラムが大きくなると、同じ名前のクラスやメソッドが別の場所で出てくることがあります。
例えば、あなたが作ったPlayerクラスと、別のライブラリにあるPlayerクラスが衝突してしまうかもしれません。
namespaceを使えば、それらを区別できます。

2. 例でイメージ

namespace Game.Characters
{
    public class Player
    {
        public void Jump()
        {
            Console.WriteLine("Jump!");
        }
    }
}
namespace Game.UI
{
    public class Player
    {
        public void ShowStatus()
        {
            Console.WriteLine("Showing player status");
        }
    }
}

上の例では、Playerクラスが2つありますが、

  • Game.Characters.Player → ゲームのキャラとしてのプレイヤー
  • Game.UI.Player → UI表示用のプレイヤー情報

というように、namespaceによって衝突を回避できます。

3. 呼び出し方

// 名前空間を指定して使う
var player1 = new Game.Characters.Player();
var player2 = new Game.UI.Player();

// usingで短く書く
using Game.Characters;

var player3 = new Player(); // Game.Characters.Playerを指す

4. 実はフォルダと1対1じゃない

よく誤解されますが、namespaceの階層構造はフォルダと一致する必要はありません。
ただし、分かりやすく管理するために、フォルダ構造とnamespaceを合わせることが多いです。

5. イメージで分かりやすく

namespaceがない場合
image.png

namespaceがある場合
image.png

6. まとめ

  • namespaceはクラスや関数の「住所」
  • 名前の衝突を防ぐ
  • usingを使うと短く書ける
  • フォルダ構造と必ずしも一致しない(けど合わせるのが普通)
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?