2
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# - int 型って null と同値比較できるんですね (できてるとは言えない

Posted at

ずばり、表題のとおりです。以下のような C# コードが、ビルドできて実行できます。

var n = 123;
if (n == null) Console.WriteLine("n は null です");
if (n != null) Console.WriteLine("n は null じゃありません");

自分は言われるまで、上記コードがビルドできて実行できるとは知りませんでした。int って C# でいう値型なので、つまり参照型ではないので、そもそも null と比較できるとは思ってもみませんでした。

ただし、C# の構文・仕様的には上記コードが許されるとはいっても、int 型のような値型が null になることは決してないので、n == null が真になることは決してありません (その逆で、n != null は常に真ですね)。

なので、VSCode など C# の LSP が動作する高機能エディタや IDE 上では下図のように CS0472 の警告が表示されます。

もちろん、ビルド時にもこの警告は表示されます。CS0472 警告について公式ドキュメントはこちら。

知ってどうするという知識でもないのですが、自分的にはちょっとびっくりで新鮮だったので、メモ書きまでに。

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