Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

ref: practical reference

ref: practical reference: ref passes or returns an alias to an existing storage location instead of a copy.

Version: C# language; verified against C# 14 reference

Syntax

ref /* grammar-specific form */

ref passes or returns an alias to an existing storage location instead of a copy.

Use it for efficient mutation of large structs and span-oriented APIs with controlled lifetime.

An alias can break invariants and complicate reasoning; it must not outlive its referent.

A ref local must be initialized by a reference, and ref return follows escape analysis.

The complete program actually uses ref; its exact expected stdout is 7.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

var value = 2; ref var alias = ref value; alias = 7; Console.WriteLine(value);

Result

7

The complete program actually uses `ref`; its exact expected stdout is `7`.

Sources