References
A reference aliases an existing value while preserving typed member access and overload resolution.
Binding a reference
Add & to a type to declare a reference. A reference must be initialized from a compatible value and does not create a copy.
int value = 10;
int& alias = value;
alias = 42; // value is now 42
References use normal value syntax: member access is written with ., and a reference is passed to a T& parameter without an explicit address-of operator.
Mutable and readonly references
A mutable T& permits writes to the referenced value. A readonly T& permits reads but not mutation through that reference.
void Increment(int& value)
{
value += 1;
}
int Read(readonly int& value)
{
return value;
}
A mutable reference converts to a readonly reference. The reverse conversion is not allowed because it would restore write access.
Struct and interface references
References preserve polymorphic conversions. A derived struct reference may bind to a base struct reference, and a struct reference may bind to an interface reference implemented by that struct.
Sprite sprite = Sprite(true);
IRenderable& renderable = sprite;
renderable.Render();
Calls through an interface reference use the concrete struct's implementation. Readonly receivers may call members whose contract is declared readonly.
Returning references
Functions and methods may return references, allowing callers to keep aliasing an existing field or value.
struct Container
{
private int value;
public int& Get()
{
return value;
}
}
A reference does not own storage and is not released with free. The referenced value must remain alive for every use of the reference.