Skip to content

ES CSharp Keyword readonly

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

C#: readonly

Manual C# · Guía Práctica

Prohíbe el reemplazo de campos después de la inicialización o el constructor; También describe estructuras inmutables y acceso de referencia de solo lectura.

Ejemplo sencillo (Example.cs)

Guarde este ejemplo por separado como Example.cs. Ejecútelo independientemente de los demás ejemplos de esta página.

Example.cs:

// PROJECT-EXAMPLE
System.Console.WriteLine(new Item(7).Count);
class Item { public readonly int Count; public Item(int count) { Count = count; } }

Resultado:

7

Sintaxis

readonly Type field; / readonly struct Type / ref readonly Type

una referencia de solo lectura a una lista no hace que los elementos de la lista sean inmutables. Para ser constante, el valor debe conocerse en el momento de la compilación.

Ejemplo 1: forma básica

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Settings settings = new("profile");
        Console.WriteLine(settings.Name);
    }
}
public class Settings(string name) { public readonly string Name = name; }

Ejemplo 2: otra forma práctica

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

public static class Program
{
    public static async Task Main(string[] args)
    {
        Position position = new(2, 3);
        Console.WriteLine(position.Sum);
    }
}
public readonly struct Position(int x, int y) { public int X { get; } = x; public int Y { get; } = y; public int Sum => X + Y; }

Fuente oficial: Microsoft Aprender.

Clone this wiki locally