[C#] Null 非許容の値型であるため、null を 'int' に変換できません

参照型は null が許容されているが、値型は null が許容されていない。この制約は、null 許容型を使用することで回避できる。回避するだけならね。
 int? i = null;
 int? j = 3;
 System.Diagnostics.Debug.WriteLine(i + j);
 // 出力: null
この、?マークがついた宣言が null 許容型となる。値が入っていれば、そのままその値が評価されるが、null の場合は評価されない。上記の例でいうと、計算自体が行われないで null として評価されるのだ。
また、null 許容型は、三項演算子のように条件式を書くことができる。
 int? i = null;            
 System.Diagnostics.Debug.WriteLine(i ?? 0);
 // 出力: 0
null 許容型については、@IT の記事が参考になる。

for Visual Basic
 ' VB の場合、null 許容型は以下の書き方ができる。
 Dim i As Integer? = Nothing
 Dim ii? As Integer = Nothing
 Dim iii As Nullable(Of Integer) = Nothing

 Dim j As Integer = 3
 System.Diagnostics.Debug.WriteLine(i + j)
 ' null 許容型の判断(VB)
 Dim k As Integer? = Nothing
 System.Diagnostics.Debug.WriteLine(If(k, 0))

このブログの人気の投稿

コピーした行の挿入が表示されない時はフィルタされていないかチェック

Excel で一部の図形だけ固定する