Skip to content

Commit 8411a1c

Browse files
Add example demonstrating generic extension blocks (#50069)
* Add example demonstrating generic extension blocks * Update docs/csharp/programming-guide/classes-and-structs/extension-methods.md --------- Co-authored-by: Bill Wagner <wiwagn@microsoft.com>
1 parent 429355e commit 8411a1c

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

docs/csharp/programming-guide/classes-and-structs/extension-methods.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: "Extension members"
33
description: Extension members in C# enable you to add methods, properties, or operators to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
4-
ms.date: 09/17/2025
4+
ms.date: 11/20/2025
55
helpviewer_keywords:
66
- "methods [C#], adding to existing types"
77
- "extension methods [C#]"
@@ -34,6 +34,10 @@ Beginning with C# 14, you can declare *extension blocks*. An extension block is
3434

3535
:::code language="csharp" source="./snippets/ExtensionMembers/CustomExtensionMembers.cs" id="ExtensionBlock":::
3636

37+
Extension members in an extension block can use open or closed generics. The type parameters can include constraints:
38+
39+
:::code language="csharp" source="./snippets/ExtensionMembers/CustomExtensionMembers.cs" id="GenericExtensionBlock":::
40+
3741
Before C# 14, you declare an extension method by adding the `this` modifier to the first parameter:
3842

3943
:::code language="csharp" source="./snippets/ExtensionMembers/CustomExtensionMethods.cs" id="ClassicExtensionMethod":::

docs/csharp/programming-guide/classes-and-structs/snippets/ExtensionMembers/CustomExtensionMembers.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,18 @@ public int WordCount() =>
1111
}
1212
// </ExtensionBlock>
1313

14+
// <GenericExtensionBlock>
15+
public static class MyGenericExtensions
16+
{
17+
extension<T>(IEnumerable<T> source)
18+
where T : IEquatable<T>
19+
{
20+
public IEnumerable<T> ValuesEqualTo(T threshold)
21+
=> source.Where(x => x.Equals(threshold));
22+
}
23+
}
24+
// </GenericExtensionBlock>
25+
1426
public interface IMyInterface
1527
{
1628
void MethodB();

0 commit comments

Comments
 (0)