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#】NullReferenceExceptionの原因と対処法まとめ【初心者向け】

0
Posted at

はじめに

C#で開発していると、NullReferenceException に遭遇することがよくあります。
この記事では、よくある原因とその対処法を実例付きで紹介します。


NullReferenceExceptionとは?

NullReferenceException は、nullのオブジェクトにアクセスしようとしたときに発生する例外です。

string message = null;
Console.WriteLine(message.Length); // ← ここで例外が発生

よくある原因と対処法

1. オブジェクトの初期化忘れ

MyClass obj = null;
obj.DoSomething(); // NullReferenceException

✅ 対処法

MyClass obj = new MyClass();
obj.DoSomething(); // OK

2. 配列やリストの要素がnull

string[] names = new string[3];
Console.WriteLine(names[0].Length); // NullReferenceException

✅ 対処法

if (names[0] != null)
{
    Console.WriteLine(names[0].Length);
}

3. LINQのFirstOrDefault()の扱い

var user = users.FirstOrDefault(u => u.Id == 1);
Console.WriteLine(user.Name); // userがnullの可能性あり

✅ 対処法

if (user != null)
{
    Console.WriteLine(user.Name);
}

4. クラスのプロパティがnull

public class Order
{
    public Customer Customer { get; set; }
}

var order = new Order();
Console.WriteLine(order.Customer.Name); // NullReferenceException

✅ 対処法

if (order.Customer != null)
{
    Console.WriteLine(order.Customer.Name);
}

5. null条件演算子(?.)の活用
C# 6以降では、nullチェックを簡潔に書ける ?. 演算子が使えます。

Console.WriteLine(order?.Customer?.Name);

まとめ

  • NullReferenceException は「nullにアクセスした」ことが原因
  • 初期化忘れ・nullチェック漏れ・LINQの戻り値に注意
  • *nullable reference types(C# 8以降)*の活用もおすすめ
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?