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 3 years have passed since last update.

【備忘録】動的型付けと型推論の違い

Last updated at Posted at 2021-02-21

はじめに

C#を勉強してると、
「varって動的型付けじゃないの?」

「C#だとdynamicが動的型付けで、varは型推論なんだ」

「てか、動的型付けと型推論って違うのか!」
となり、違いを理解していなかったので調べてみました。
ざっくりとした説明なので、詳しく知りたい人は自分で調べてちょ。

動的型付け

実行時(Console.Write時)に型が決定されます。なので、下記のようになります。

// C#
dynamic x = 100  // 動的型付けにより、変数xの型が数値型に決定する
x = "Hello World !"  // 型が動的に決定されるので、エラーがにならず変数xの型が文字列型になる

Console.Write(x)  // 「Hello World !」が表示される

型推論

コンパイル時(上からコードが読み込まれる時)に型が決定されます。

// C#
var x = 100  // Int型を指定しなくても、代入される値からコンパイラが変数xの型を自動で決定する(型推論)
x = "Hello World !"   // 型推論によりxがInt型に決定されているため、Int型以外を代入するとコンパイルエラーが発生

Console.Write(x) // コンパイルエラーのため実行できない

補足

しかしながら、あくまで型推論である var と違って、dynamic で宣言した変数の型は「動的型」になります。

var sx = 1;     // sx の型は int 型
dynamic dx = 1; // dx の型は dynamic 型
0
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
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?