Skip to content

static examples #45642

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
Apr 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/csharp/language-reference/keywords/static.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@ Use the `static` modifier to declare a static member, which belongs to the type

You can add the `static` modifier to a [local function](../../programming-guide/classes-and-structs/local-functions.md). A static local function can't capture local variables or instance state.

[!code-csharp[csrefKeywordsModifiers#28](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsModifiers/CS/csrefKeywordsModifiers.cs#28)]

You can add the `static` modifier to a [lambda expression](../operators/lambda-expressions.md) or [anonymous method](../operators/delegate-operator.md). A static lambda or anonymous method can't capture local variables or instance state.

[!code-csharp[csrefKeywordsModifiers#29](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csrefKeywordsModifiers/CS/csrefKeywordsModifiers.cs#29)]

## Example - static class

The following class is declared as `static` and contains only `static` methods:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -818,4 +818,46 @@ public static void Main(string[] args)
}
//</snippet27>
}

//<snippet28>
class Calc1
{
public void CalculateSum()
{
int a = 3;
int b = 7;

// Static local function - cannot access 'a' or 'b' directly
static int Add(int x, int y)
{
return x + y;
}

int result = Add(a, b);
Console.WriteLine($"Sum: {result}");
}
}
/*
Output:
Sum: 10
*/
//</snippet28>


//<snippet29>
class Calc2
{
static void Main()
{
Func<int, int, int> add = static (a, b) => a + b;

int result = add(5, 10);
Console.WriteLine($"Sum: {result}");
}
}
/*
Output:
Sum: 15
*/
//</snippet29>
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net48</TargetFramework>
<TargetFramework>net9.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StartupObject>csrefKeywordsModifiers.UsingTest</StartupObject>
</PropertyGroup>
Expand Down