16

I'm reading the description of the new feature in C# 8 called nullable reference types. The description discusses so called null-forgiving operator. The example in the description talks about de-referencing of an instance of a reference type (I think so):

Microsoft Docs

You can also use the null-forgiving operator when you definitely know that an expression cannot be null but the compiler doesn't manage to recognize that. In the following example, if the IsValid method returns true, its argument is not null and you can safely dereference it:

public static void Main() 
{
   Person? p = Find("John");
   if (IsValid(p))
   {
       Console.WriteLine($"Found {p!.Name}");
   } 
}
public static bool IsValid(Person? person) 
{
   return person != null && !string.IsNullOrEmpty(person.Name); 
}

Without the null-forgiving operator, the compiler generates the following warning for the p.Name code: Warning CS8602: Dereference of a possibly null reference.

I was under impression that in C# dereferencing an object means setting it to null. But it looks like Microsoft calls accessing an object's property as dereferencing the object.

The question is: what does mean the dereferencing term in C# when we are talking about a reference type instances, not about pointers managed and unmanaged.

Toni
  • 1,555
  • 4
  • 15
  • 23
usr2020
  • 324
  • 2
  • 8
  • 9
    Q: c# dereferencing an object means setting it to null. A: No, absolutely not. "Dereferencing an object" means "obtain the variable pointed by a pointer": https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/pointer-related-operators. And yes, "dereferencing" applies to "reference type instances". – paulsm4 Sep 24 '20 at 16:01
  • @paulsm4 I'd say that's as good an answer as any, you should move it to an answer to get the rep :-). – AStopher Sep 24 '20 at 16:04

1 Answers1

17

Dereferencing means following the reference to access the actual underlying object. If the reference is null, this causes a big problem.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Hello. What the problem can we get If the reference is null? Can you give me some links where to read about it? – Владимир Береза Dec 21 '21 at 10:30
  • @ВладимирБереза This will result in a NullReferenceException: https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception?view=net-7.0 A NullReferenceException exception is thrown when you try to access a member on a type whose value is `null`. – Niels R. Jan 02 '23 at 08:03
  • @NielsR. Thank's. Ofcourse i know about NullReferenceException and how to prevent it. But Joel Coehoorn said about the big problem. Maybe he meant something else in some scenarios. – Владимир Береза Jan 19 '23 at 11:27