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: WarningCS8602
: 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.
Dereferencing a variable means accessing the variable stored at a memory address: int i = 5; int * p; p = &i; *p = 7; //*p returns the variable stored at the memory address stored in p, which is i. //i is now 7.
Dereferencing means taking away the reference and giving you what it was actually referring to. A pointer to something really means that your pointer variable holds a memory address of something . But the pointer can also be thought of as a reference to something instead.
To go to an address before performing the operation. For example, in C programming, a dereferenced variable is a pointer to the variable, not the variable itself.
Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator.
Dereferencing means following the reference to access the actual underlying object. If the reference is null
, this causes a big problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With