Repository navigation
EN CSharp Keyword scoped
Codex edited this page Oct 11, 2026
·
2 revisions
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
scoped limits the valid lifetime of a reference or ref-like parameter value. The compiler will not allow such a reference to be returned in a way that exceeds the set lifetime. The modifier does not make the data immutable: the scoped ref allows changing the value of the caller.
Save this example separately as Example.cs. Run it independently of the other examples on this page.
Example.cs:
// PROJECT-EXAMPLE
void Add(scoped ref int value) { value += 2; }
int count = 3;
Add(ref count);
System.Console.WriteLine(count);Result:
5
static int Sum(scoped ReadOnlySpan<int> values);
static void Add(scoped ref int value, int amount);using System;
internal static class Program
{
public static void Main()
{
ReadOnlySpan<int> readings = stackalloc int[] { 3, 5, 7 };
Console.WriteLine(Sum(readings));
}
private static int Sum(scoped ReadOnlySpan<int> values)
{
int total = 0;
foreach (int value in values) total += value;
return total;
}
}Result:
15
using System;
internal static class Program
{
public static void Main()
{
int points = 10;
Add(ref points, 4);
Add(ref points, 6);
Console.WriteLine(points);
}
private static void Add(scoped ref int value, int amount)
{
value += amount;
}
}Result:
20
Official source: Microsoft Learn.
ClassicUO — Bad Newbie & C# Scripts IDE