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 1 year has passed since last update.

【C#の細かいポイント】nullを適切に扱う方法

Last updated at Posted at 2024-02-13

皆さんはきっとこんな例外に遭遇したことがありますよね:未将对象引用到实例(System.NullReferenceException:“Object reference not set to an instance of an object.”)。そう、これは全てのC#プログラマーにとって馴染み深い例外でしょう。でも、ベテランであっても完全に防ぐことはできません。
まず、値型は直接nullにはできません。型の後に「?」を加えることで、可null値型に拡張します:

int i1 = default; 
Console.WriteLine(i1); 
int? i2 = null; 
Console.WriteLine(i2 ?? 0);
Console.WriteLine(i2.HasValue ? i2.Value : 0);

参照型は本来nullにできますが、ここでは少し問題があります。nullを防ぐためには、すべてのサードパーティの呼び出し箇所で、返り値が参照型の場合は空判定を加える必要がありますが、これはかなりの作業量になります。そこで、参照型を定義する際に型の後ろに「?」を加えることで、結果がnullを含むかどうかを区別し、この方式を使って空判定を行うと、かなり楽になります。

string? s1 = string.Empty; 
Console.WriteLine(s1.Length); 
string? s2 = default; 
Console.WriteLine((s2 ?? string.Empty).Length);
Console.WriteLine(string.Empty == "");//true
Console.WriteLine(string.Equals(string.Empty, ""));//true
Console.WriteLine(string.Empty == null);//false
Console.WriteLine(string.Equals(string.Empty, null));//false

以下は自作の型Orderです:

public record Order(int Id, string Name, string? Description = null);

単一エンティティをクエリする場合、nullが許容される場合はOrder?として定義し、呼び出し箇所では空判定が必要です。戻り値がOrderの場合、戻り値がnullでないことを保証する必要があります。

Order? GetOrder1()
{ 
    return default(Order); 
    //return null;
} 
Order GetOrder2()
{ 
    return new Order(default, string.Empty, default);
}

コレクションの場合、nullでないコレクションを返すには、次のような形式で空でないコレクションを返します。このコレクションはnullではなく、要素数は0です。

IEnumerable<Order> GetOrders1()
{
    return Enumerable.Empty<Order>();
} 
IList<Order> GetOrders2()
{
    return new List<Order>();
} 
Order[] GetOrders3(){ 
    // return new Order[0]; 
    return Array.Empty<Order>();
}

(Translated by GPT)
元のリンク:https://mp.weixin.qq.com/s?__biz=MzA3NDM1MzIyMQ==&mid=2247487196&idx=1&sn=7e571eada81fbc8fe69aa91caf62e30b&chksm=9f0051f6a877d8e09806a7fac093fcbe9fa5193c61f279bbe788a19b8b737f60508c69065a90&token=2050451386&lang=zh_CN#rd

0
0
3

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?