Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

readonly: practical reference

readonly: practical reference: readonly prevents field reassignment after construction or marks a non-mutating struct or member.

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

Syntax

readonly /* grammar-specific form */

readonly prevents field reassignment after construction or marks a non-mutating struct or member.

Use it to preserve references and reduce defensive copies in a readonly struct.

A readonly reference does not freeze the object it points to.

The field may be assigned in a constructor; a readonly member cannot mutate this.

The complete program actually uses readonly; its exact expected stdout is 2.

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 point = new Point(2); Console.WriteLine(point.X);
readonly record struct Point(int X);

Result

2

The complete program actually uses `readonly`; its exact expected stdout is `2`.

Sources