0
0

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#】型推論 var は使うべき?

Last updated at Posted at 2025-10-04

var を使うメリット

1. コードがスッキリする

型名を繰り返す必要がなくなるため、冗長さを減らせます。

// varを利用しない
Dictionary<string, List<int>> dict = new Dictionary<string, List<int>>();

// varを利用する
var dict = new Dictionary<string, List<int>>();

2. 型が明らかなときに読みやすい

右辺を見れば一目で型が分かる場合、型名を省略することでコードの意図がスッと入ってきます。

var user = new User();
var count = 0;
var name = "太郎";

3. 型変更に強い

右辺の型を変えても、左辺を書き換える必要がありません。

// 修正前
List<int> numbers = new List<int>();

// 型を HashSet に変えた場合
// varを利用しない
HashSet<int> numbers = new HashSet<int>();

// varを利用する(varを使うと楽)
var numbers = new HashSet<int>();

var のデメリット

1. 型が分かりにくいケースがある

右辺を見ても型が直感的に分からない場合、可読性を下げます。

var result = SomeApi.GetData();  // これ何型…?

2. 暗黙的に違う型になるリスク

リテラルの型に注意が必要です。

var num = 0;   // int になる
var big = 0L;  // long になる

まとめ:var は「読みやすさ重視」で使うべき

  • 右辺で型が明らかなとき → var を積極的に使う
  • 型が分かりにくいとき → 明示的に型を書く
  • チームのコーディング規約に合わせることが最優先

つまり、var は「楽をするため」ではなく、読みやすさを高めるためです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?