0Pricing
C# Academy · レッスン

Nullable reference types(認識)と注釈(C# 6パターン)

C# 6にはnullable reference types(string?)がありません。入力ガード、明確なドキュメント、ヘルパーのRequire.NotNullを使った安全なnull処理と、値型のNullable との違いを学びます。

「Nullable reference types(認識)と注釈(C# 6パターン)」はCoddyKit上の無料C# Academyレッスンです。 これはレッスン3/3です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはC# Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 C# Academyコースには全3レッスンが含まれています。

NRT の理解と代替策

考え方: Nullable reference types(例: string?)は、新しい C# でコンパイラーによるチェックを追加します。

  • C# 6 は string? をサポートしていません。
  • null チェック、わかりやすいドキュメント、シンプルなヘルパーを使用します
  • デフォルトでは null でない値を返します

null を防ぐガード

参照型のパラメーターには ArgumentNullException のガードを追加し、その後は値が null でないものとして扱います。

using System;

public static class Greeter
{
  // Contract: name must not be null (C# 6 has no string? to enforce)
  public static string Hello(string name)
  {
    if (name == null) throw new ArgumentNullException("name"); // guard
    return "Hello " + name.ToUpper(); // safe after guard
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Console.WriteLine(Greeter.Hello("Ada"));
    try
    {
      Console.WriteLine(Greeter.Hello(null)); // will throw (by design)
    }
    catch (Exception ex)
    {
      Console.WriteLine("Caught: " + ex.GetType().Name);
    }
  }
}

Require.NotNull ヘルパー

小さな Require.NotNull ヘルパーを作成すると、定型コードを減らし、意図を明確にできます。

using System;

public static class Require
{
  // Works for reference types; returns the validated value
  public static T NotNull<T>(T value, string name) where T : class
  {
    if (value == null) throw new ArgumentNullException(name);
    return value;
  }
}

public sealed class Email
{
  public string Address { get; private set; }

  public Email(string address)
  {
    Address = Require.NotNull(address, "address").Trim();
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Email e = new Email("user@mail.com");
    Console.WriteLine(e.Address);
  }
}

Nullable&lt;T&gt; と参照型

Nullable<T>(例: int?)は値型に使用します。参照型はもともと null になれるため、C# 6 ではガードを使用します。

using System;

public class Program
{
  public static void Main(string[] args)
  {
    int x = 5;              // value type (non-nullable)
    int? maybe = null;      // Nullable<T> works for value types
    Console.WriteLine("x=" + x);
    Console.WriteLine("maybe has value? " + maybe.HasValue);
    Console.WriteLine("maybe or default: " + (maybe ?? -1));
  }
}

null の契約をドキュメント化

XML ドキュメントで null 許容性を明記し、一貫性を保ちます。常に null でない値を返すか、null になる可能性がある場合を明確に記載してください。

using System;

/// <summary>
/// Parses "key=value" and returns the value part.
/// Returns null if the format is invalid.
/// </summary>
public static class Parser
{
  // Explicitly document when null can be returned.
  public static string TryGetValue(string line)
  {
    if (line == null) throw new ArgumentNullException("line");
    int idx = line.IndexOf("=");
    if (idx < 0 || idx == line.Length - 1) return null; // documented nullable return
    return line.Substring(idx + 1);
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Console.WriteLine(Parser.TryGetValue("a=1"));
    Console.WriteLine(Parser.TryGetValue("oops")); // prints nothing (null)
  }
}

null 安全性チェックリスト(C# 6)

チェックリスト:

  • 入力値を ArgumentNullException でガードします。
  • デフォルトでは null でない値を返し、null になり得る戻り値はドキュメント化します。
  • 小さなヘルパー(Require.NotNull)を使用して、コードを簡潔に保ちます。
  • 妥当な場合は、null を避けるオーバーロード(例: null ではなく空文字列を使用するもの)を優先します。

C# 6 での null 安全性

簡単な確認です。Nullable reference types がない C# 6 で、公開 API における null 関連のバグを減らすには、どのような実践が適切でしょうか?

まとめ

まとめ: NRT は新しい機能です。C# 6 では、ガード、わかりやすいドキュメント、ヘルパーメソッド、そして予測可能な null でない戻り値の契約を使用して安全性を保ちます。

よくある質問

「Nullable reference types(認識)と注釈(C# 6パターン)」レッスンは無料ですか?

はい。「Nullable reference types(認識)と注釈(C# 6パターン)」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、C# Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 C# Academyコースには全3レッスンが含まれています。

「Nullable reference types(認識)と注釈(C# 6パターン)」で何を学びますか?

C# 6にはnullable reference types(string?)がありません。入力ガード、明確なドキュメント、ヘルパーのRequire.NotNullを使った安全なnull処理と、値型のNullable との違いを学びます。 ブラウザで直接実行するハンズオンコードでC# Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

C# Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのC# Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/3です。

「Nullable reference types(認識)と注釈(C# 6パターン)」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このC# Academyレッスンでコードを書いて実行できますか?

はい。すべてのC# Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. ジェネリックメソッド/型と制約
  2. インターフェースとデリゲートにおける変性(in/out)
  3. Nullable reference types(認識)と注釈(C# 6パターン)
← C# Academyに戻る