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?

More than 5 years have passed since last update.

csharp > 既定値 > 数値:0 / 論理値: false / 参照型: null / 構造体: すべてを規定値で初期化 > var n = default(int); // (int)0

Last updated at Posted at 2015-08-26

引用: 即効入門 C#プログラミング すぐに現場で使える知識 by 中 博俊さんら
3.10 既定値

C#には、既定値(数値の場合は0, 論理値論理型の場合はfalse, 参照型の場合はnull, 構造体の場合はすべてのフィールドを既定値で初期化したもの)を取得するための、default式というものがあります。

var n = default(int);  // (int)0
var s = default(string); // (string)null;

ideoneで実装してみた。
http://ideone.com/1LktI3

いまいち使いどころが分からない。default(int)とか書くと「default値ってなんだ?」ということになるのでvar n = (int)0;など書いたほうがいいように思う。

あるいは、「この値はdefault値に戻している」という意図をコードとして残すのだろうか? n = 0;と書いた時「0ってなんだ?」になるより、n = default(int)として「デフォルト値に戻しているのか」と分かる? ただ、その場合でも、自分でconst定義した数値を入れるほうがデフォルト値を0以外にできるだろう。


(追記 2015/08/27) @potimarimo さんのコメントにより、上記の疑問が解決しました。

ジェネリックの場合、既定値を0などで設定しているとまずいのでdefault()が役に立つということでした。

0
0
4

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?