2
4

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#】`using` エイリアスで名前空間やクラスを簡潔に扱う方法

Posted at

【C#】using エイリアスで名前空間やクラス名を省略してスッキリ書く方法

C#では、長い名前空間やクラス名を簡潔に書くために「using エイリアス(別名)」を使うことができます。この記事では、特に 名前空間全体へのエイリアス特定クラスへのエイリアスの違いについて、実例とともに解説します。


1. 名前空間に対する using エイリアス

以下のように書くと、名前空間全体に別名を付けることができます:

using Responses = YourCompany.YourProject.Api.Models.Responses;

これにより、コード内では Responses という短い名前で名前空間を扱えるようになります。

使用例

var result = new Responses.MyResponseModel();

これは実際には以下と同じです:

var result = new YourCompany.YourProject.Api.Models.Responses.MyResponseModel();

メリット:何度も長い名前空間を書く必要がなく、コードがスッキリします。


2. クラスに対する using エイリアス

もし 特定のクラスにだけ別名を付けたい場合は、以下のように書きます:

using MyResponse = YourCompany.YourProject.Api.Models.Responses.MyResponseModel;

使用例

var result = new MyResponse();

こちらは、クラス自体に直接エイリアスを付ける形です。


3. 両者の違いまとめ

種類 書き方 使用例 説明
名前空間へのエイリアス using 別名 = 名前空間; Responses.MyClass 名前空間全体の省略
クラスへのエイリアス using 別名 = クラス名; MyResponse 特定クラス名の省略

4. どちらを使うべき?

  • 同一の名前空間に複数のクラスがあり、繰り返し使う場合 → 名前空間にエイリアス
  • 特定のクラスだけを頻繁に使う場合 → クラスにエイリアス

5. まとめ

using エイリアスは、読みやすくメンテナンスしやすいC#コードを書くうえでの強力なツールです。状況に応じて、名前空間全体かクラス個別かを使い分けるようにしましょう。

2
4
1

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
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?