Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / C#

this: riferimento pratico

this: riferimento pratico: this indica l’istanza corrente o concatena la costruzione a un altro costruttore.

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

Sintassi

this /* grammar-specific form */

this indica l’istanza corrente o concatena la costruzione a un altro costruttore.

Usalo per distinguere un campo da un parametro e mantenere coerente la catena dei costruttori.

Non è disponibile in contesto static; far sfuggire this dal costruttore espone un oggetto incompleto.

In una struct, this ha semantica di valore e rispetta le restrizioni readonly.

Il programma completo usa realmente this; lo stdout esatto atteso è 4.

Esempi

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;

Console.WriteLine(new Box(4).Read()); sealed class Box { private readonly int value; public Box(int value) => this.value = value; public int Read() => this.value; }

Risultato

4

Il programma completo usa realmente `this`; lo stdout esatto atteso è `4`.

Fonti