What Does Indirection operator Mean?
An indirection operator, in the context of C#, is an operator used to obtain the value of a variable to which a pointer points. While a pointer pointing to a variable provides an indirect access to the value of the variable stored in its memory address, the indirection operator dereferences the pointer and returns the value of the variable at that memory location. The indirection operator is a unary operator represented by the symbol (*).
The indirection operator can be used in a pointer to a pointer to an integer, a single-dimensional array of pointers to integers, a pointer to a char, and a pointer to an unknown type.
The indirection operator is also known as the dereference operator.
Techopedia Explains Indirection operator
The (*) symbol is used in declaring pointer types and in performing pointer indirection, while the ‘address-of’ operator () returns the address of a variable. Hence, the indirection operator and the address-of operator are inverses of each other.
C# allows using pointers only in an unsafe region, which implies that the safety of the code within that region is not verified by the common language runtime (CLR). In the unsafe region, the indirection operator is allowed to read and write to a pointer. The following C# statements illustrate the usage of the indirection operator:
- int a = 1, b; // line 1
- int *pInt = &a; // line 2
- b = *pInt; // line 3
In the first line above, a and b are integer variables and a is assigned a value of 1. In line 2, the address of a is stored in the integer pointer pInt (line 2). The dereference operator is used in line 3 to assign the value at the address pointed to by pInt to the integer variable b.
The indirection operator should be used to dereference a valid pointer with an address aligned to the type it points to, so as to avoid undefined behavior at runtime. It should not be applied to a void pointer or to an expression that is not of a pointer type, to avoid compiler errors. However, after casting a void pointer to the right pointer type, the indirection operator can be used.
When declaring multiple pointers in a single statement, the indirection operator should be written only once with the underlying type and not repeated for each pointer name. The indirection operator is distributive in C#, unlike C and C++. When the indirection operator is applied to a null pointer, it results in an implementation-defined behavior. Since this operator is used in an unsafe context, the keyword unsafe should be used before it along with the /unsafe option during compilation.