Reputation: 241
are there reference or pointer in C#? (without using /unsafe) e.g.,
Dog a = new Dog()
Dog b = a;
Would b point to a? When are there this kind of pointers/references? (If there are at all) Sorry for the probably silly question. Thank you!
Upvotes: 1
Views: 189
Reputation: 54453
In other languages a Pointer is a variable that holds a memory address .
In C# a reference doesn't point to a memory address but to an object.
The memory address where that object happens to be stored at is a highly volatile thing, likely to change at any time and for a number of reasons, unless you pin the object by using fixed
:
The fixed statement sets a pointer to a managed variable and "pins" that variable during the execution of statement. Without fixed, pointers to movable managed variables would be of little use since garbage collection could relocate the variables unpredictably. The C# compiler only lets you assign a pointer to a managed variable in a fixed statement.
Therefore one could say that without using fixed
code there really are no pointers.
Upvotes: 0
Reputation: 113392
It depends on what Dog
is.
If Dog
is a reference-type defined with class Dog
then a
and b
are both references to the same object. This object is on the heap and will be eligible for collection the moment no such references could be used by any code*.
If Dog
is a value-type defined with struct Dog
then b
is a copy of a
.
There are other types of references such as:
void DoSomething(Dog a, ref Dog b)
{
b = a;
}
Here b
is a reference parameter, so either a reference to a reference type, or a reference to a value type, depending on the definition of Dog
as above.
The result of indexing an array is also a reference type, allowing one to mutate a mutable value-type stored within an array, though mutable value types are of limited value (there are times when they're useful but they often cause confusion and are generally best never exposed by an assembly).
*Generally, there's no such references in static variables, no such references in locals that are potentially going to be used again, or no fields in classes that are in turn reachable in one of those ways.
Upvotes: 1
Reputation: 203847
b
does not point to a
, no, b
points to the object referenced by a
at the time of the assignment. Changes in the variable a
will not be observable through b
. Changes to the object referenced by a
will be observable to b
.
There are ways to reference a
(the variable, not the value it references) though. One being a lambda:
Func<Dog> c = () => a;
Whenever c
is invoked, it will return the value of a
at the time of invocation not at the time the delegate is constructed, because lambdas close over variables and not values.
Upvotes: 8