C# and Null object

There is a lot to talk i n programming that null is bad,for example https://www.yegor256.com/2014/05/13/why-null-is-bad.html   and https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/ .

In C# we have a love-hate relationship with null :

Love : Because  the value type / struct cannot be null,C# creators invented Nullable<T> https://docs.microsoft.com/en-us/dotnet/api/system.nullable-1

Hate: Because  reference types / classes can be null,c# 8.0 invented nullable reference types : https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/nullable-reference-types – no doubt from me that will be in the language

I want to add my 2 cents here : Null is sometime good

1. For databases,a null field is different from a 0 field ( see this toilet paper null vs 0 as a reference : https://pbs.twimg.com/media/C7ojxbSVAAEX9Bt.jpg )

2. For finding if a item exists in an array of value types,how do you find that the value that you want to search exists or not with .FirstOrDefault ? If the array is composed of reference,you can compare with null ….


Posted

in

,

by

Tags:

Comments

2 responses to “C# and Null object”

  1. Tudor Avatar
    Tudor

    I’ve met developers who consider methods like FirstOrDefault() as antipatterns..
    They prefer to start with a if Contains() followed by a First()
    and optimize later if really necessary..

    1. Andrei Ignat Avatar
      Andrei Ignat

      Contains for struct ? You will have the same problem ….

Leave a Reply

Your email address will not be published. Required fields are marked *