Skip to content

Commit 750e846

Browse files
committed
First draft of the language reference
1 parent f1993b1 commit 750e846

File tree

3 files changed

+119
-128
lines changed

3 files changed

+119
-128
lines changed

docs/csharp/language-reference/keywords/extension.md

+18-123
Original file line numberDiff line numberDiff line change
@@ -8,148 +8,43 @@ f1_keywords:
88
---
99
# Extension declaration (C# Reference)
1010

11-
- Show new syntax with instance container
12-
- Show new syntax with static container
13-
- Show old syntax
14-
- Explain the lowering
11+
Beginning with C# 14, top level, non-generic `static class` declarations can use `extension` containers to declare *extension members*. Extension members are methods or properties and can appear to be instance or static members. Earlier versions of C# enable *extension methods* by adding `this` as a modifier to the first parameter of a static method declared in a top-level, non-generic static class.
1512

16-
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type. For client code written in C#, F# and Visual Basic, there's no apparent difference between calling an extension method and the methods defined in a type.
13+
The `extension` container specifies the type and receiver for extension members. You can declare methods and properties inside the `extension` declaration. The following example declares a single extension container that defines an instance extension method and an instance property.
1714

18-
The most common extension methods are the LINQ standard query operators that add query functionality to the existing <xref:System.Collections.IEnumerable?displayProperty=nameWithType> and <xref:System.Collections.Generic.IEnumerable%601?displayProperty=nameWithType> types. To use the standard query operators, first bring them into scope with a `using System.Linq` directive. Then any type that implements <xref:System.Collections.Generic.IEnumerable%601> appears to have instance methods such as <xref:System.Linq.Enumerable.GroupBy%2A>, <xref:System.Linq.Enumerable.OrderBy%2A>, <xref:System.Linq.Enumerable.Average%2A>, and so on. You can see these additional methods in IntelliSense statement completion when you type "dot" after an instance of an <xref:System.Collections.Generic.IEnumerable%601> type such as <xref:System.Collections.Generic.List%601> or <xref:System.Array>.
15+
:::code language="csharp" source="./snippets/extensions.cs" id="ExtensionMembers":::
1916

20-
### OrderBy Example
17+
The `extension` defines the receiver: `sequence`, which is the an `IEnumerable<int>`. The receiver type can be non-generic, an open generic, or a closed generic type. The name `sequence` is in scope in every instance member declared in that extension. The extension method and property both access `sequence`.
2118

22-
The following example shows how to call the standard query operator `OrderBy` method on an array of integers. The expression in parentheses is a lambda expression. Many standard query operators take lambda expressions as parameters, but this isn't a requirement for extension methods. For more information, see [Lambda Expressions](../../language-reference/operators/lambda-expressions.md).
19+
Any of the extension members can be accessed as though they were members of the receiver type:
2320

24-
[!code-csharp[csProgGuideExtensionMethods#3](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideExtensionMethods/cs/extensionmethods.cs#3)]
21+
:::code language="csharp" source="./snippets/extensions.cs" id="UseExtensionMethod":::
2522

26-
Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on. The parameter follows the [this](../../language-reference/keywords/this.md) modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a `using` directive.
23+
You can declare any number of members in a single container, as long as they share the same receiver. You can declare as many extension containers in a single class as well. Different extensions don't need to declare the same type or name of receiver. The extension parameter doesn't need to include the parameter name if the only members are static:
2724

28-
The following example shows an extension method defined for the <xref:System.String?displayProperty=nameWithType> class. It's defined inside a non-nested, non-generic static class:
25+
:::code language="csharp" source="./snippets/extensions.cs" id="StaticExtensions":::
2926

30-
[!code-csharp[csProgGuideExtensionMethods#4](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideExtensionMethods/cs/extensionmethods.cs#4)]
27+
Static extensions can be called as though they are static members of the receiver type:
3128

32-
The `WordCount` extension method can be brought into scope with this `using` directive:
29+
:::code language="csharp" source="./snippets/extensions.cs" id="UseStaticExtensions":::
3330

34-
```csharp
35-
using ExtensionMethods;
36-
```
31+
> [!IMPORTANT]
32+
> An extension doesn't introduce a *scope* for member declarations. All members declared in a single class, even if in multiple extensions, must have unique signatures. The generated signature includes the receiver type in its name for static members and the receiver parameter for extension instance members.
3733
38-
And it can be called from an application by using this syntax:
34+
The following example shows an extension method using the `this` modifier:
3935

40-
```csharp
41-
string s = "Hello Extension Methods";
42-
int i = s.WordCount();
43-
```
36+
:::code language="csharp" source="./snippets/ExtensionMethods.cs" id="ExtensionMethod":::
4437

45-
You invoke the extension method in your code with instance method syntax. The intermediate language (IL) generated by the compiler translates your code into a call on the static method. The principle of encapsulation isn't really being violated. Extension methods can't access private variables in the type they're extending.
38+
The `Add` method can be called from any other method as though it was a member of the `IEnumerable<int>` interface:
4639

47-
Both the `MyExtensions` class and the `WordCount` method are `static`, and it can be accessed like all other `static` members. The `WordCount` method can be invoked like other `static` methods as follows:
40+
:::code language="csharp" source="./snippets/ExtensionMethods.cs" id="UseExtensionMethod":::
4841

49-
```csharp
50-
string s = "Hello Extension Methods";
51-
int i = MyExtensions.WordCount(s);
52-
```
53-
54-
The preceding C# code:
55-
56-
- Declares and assigns a new `string` named `s` with a value of `"Hello Extension Methods"`.
57-
- Calls `MyExtensions.WordCount` given argument `s`.
58-
59-
For more information, see [How to implement and call a custom extension method](./how-to-implement-and-call-a-custom-extension-method.md).
60-
61-
In general, you'll probably be calling extension methods far more often than implementing your own. Because extension methods are called by using instance method syntax, no special knowledge is required to use them from client code. To enable extension methods for a particular type, just add a `using` directive for the namespace in which the methods are defined. For example, to use the standard query operators, add this `using` directive to your code:
62-
63-
```csharp
64-
using System.Linq;
65-
```
66-
67-
(You may also have to add a reference to System.Core.dll.) You'll notice that the standard query operators now appear in IntelliSense as additional methods available for most <xref:System.Collections.Generic.IEnumerable%601> types.
68-
69-
## Binding Extension Methods at Compile Time
70-
71-
You can use extension methods to extend a class or interface, but not to override them. An extension method with the same name and signature as an interface or class method will never be called. At compile time, extension methods always have lower priority than instance methods defined in the type itself. In other words, if a type has a method named `Process(int i)`, and you have an extension method with the same signature, the compiler will always bind to the instance method. When the compiler encounters a method invocation, it first looks for a match in the type's instance methods. If no match is found, it searches for any extension methods that are defined for the type, and bind to the first extension method that it finds.
72-
73-
## Example
74-
75-
The following example demonstrates the rules that the C# compiler follows in determining whether to bind a method call to an instance method on the type, or to an extension method. The static class `Extensions` contains extension methods defined for any type that implements `IMyInterface`. Classes `A`, `B`, and `C` all implement the interface.
76-
77-
The `MethodB` extension method is never called because its name and signature exactly match methods already implemented by the classes.
78-
79-
When the compiler can't find an instance method with a matching signature, it will bind to a matching extension method if one exists.
80-
81-
[!code-csharp[csProgGuideExtensionMethods#5](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideExtensionMethods/cs/extensionmethods.cs#5)]
82-
83-
## Common Usage Patterns
84-
85-
### Collection Functionality
86-
87-
In the past, it was common to create "Collection Classes" that implemented the <xref:System.Collections.Generic.IEnumerable%601?displayProperty=nameWithType> interface for a given type and contained functionality that acted on collections of that type. While there's nothing wrong with creating this type of collection object, the same functionality can be achieved by using an extension on the <xref:System.Collections.Generic.IEnumerable%601?displayProperty=nameWithType>. Extensions have the advantage of allowing the functionality to be called from any collection such as an <xref:System.Array?displayProperty=nameWithType> or <xref:System.Collections.Generic.List%601?displayProperty=nameWithType> that implements <xref:System.Collections.Generic.IEnumerable%601?displayProperty=nameWithType> on that type. An example of this using an Array of Int32 can be found [earlier in this article](#orderby-example).
88-
89-
### Layer-Specific Functionality
90-
91-
When using an Onion Architecture or other layered application design, it's common to have a set of Domain Entities or Data Transfer Objects that can be used to communicate across application boundaries. These objects generally contain no functionality, or only minimal functionality that applies to all layers of the application. Extension methods can be used to add functionality that is specific to each application layer without loading the object down with methods not needed or wanted in other layers.
92-
93-
```csharp
94-
public class DomainEntity
95-
{
96-
public int Id { get; set; }
97-
public string FirstName { get; set; }
98-
public string LastName { get; set; }
99-
}
100-
101-
static class DomainEntityExtensions
102-
{
103-
static string FullName(this DomainEntity value)
104-
=> $"{value.FirstName} {value.LastName}";
105-
}
106-
```
107-
108-
### Extending Predefined Types
109-
110-
Rather than creating new objects when reusable functionality needs to be created, we can often extend an existing type, such as a .NET or CLR type. As an example, if we don't use extension methods, we might create an `Engine` or `Query` class to do the work of executing a query on a SQL Server that may be called from multiple places in our code. However we can instead extend the <xref:System.Data.SqlClient.SqlConnection?displayProperty=nameWithType> class using extension methods to perform that query from anywhere we have a connection to a SQL Server. Other examples might be to add common functionality to the <xref:System.String?displayProperty=nameWithType> class, extend the data processing capabilities of the <xref:System.IO.Stream?displayProperty=nameWithType> object, and <xref:System.Exception?displayProperty=nameWithType> objects for specific error handling functionality. These types of use-cases are limited only by your imagination and good sense.
111-
112-
Extending predefined types can be difficult with `struct` types because they're passed by value to methods. That means any changes to the struct are made to a copy of the struct. Those changes aren't visible once the extension method exits. You can add the `ref` modifier to the first argument making it a `ref` extension method. The `ref` keyword can appear before or after the `this` keyword without any semantic differences. Adding the `ref` modifier indicates that the first argument is passed by reference. This enables you to write extension methods that change the state of the struct being extended (note that private members aren't accessible). Only value types or generic types constrained to struct (see [`struct` constraint](../../language-reference/builtin-types/struct.md#struct-constraint) for more information) are allowed as the first parameter of a `ref` extension method. The following example shows how to use a `ref` extension method to directly modify a built-in type without the need to reassign the result or pass it through a function with the `ref` keyword:
113-
114-
:::code language="csharp" source="./snippets/methods/Program.cs" id="Snippet9":::
115-
116-
This next example demonstrates `ref` extension methods for user-defined struct types:
117-
118-
:::code language="csharp" source="./snippets/methods/Program.cs" id="Snippet10":::
119-
120-
## General Guidelines
121-
122-
While it's still considered preferable to add functionality by modifying an object's code or deriving a new type whenever it's reasonable and possible to do so, extension methods have become a crucial option for creating reusable functionality throughout the .NET ecosystem. For those occasions when the original source isn't under your control, when a derived object is inappropriate or impossible, or when the functionality shouldn't be exposed beyond its applicable scope, Extension methods are an excellent choice.
123-
124-
For more information on derived types, see [Inheritance](../../fundamentals/object-oriented/inheritance.md).
125-
126-
When using an extension method to extend a type whose source code you aren't in control of, you run the risk that a change in the implementation of the type will cause your extension method to break.
127-
128-
If you do implement extension methods for a given type, remember the following points:
129-
130-
- An extension method is not called if it has the same signature as a method defined in the type.
131-
- Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named `Extensions`, they'll all be brought into scope by the `using Extensions;` directive.
132-
133-
For a class library that you implemented, you shouldn't use extension methods to avoid incrementing the version number of an assembly. If you want to add significant functionality to a library for which you own the source code, follow the .NET guidelines for assembly versioning. For more information, see [Assembly Versioning](../../../standard/assembly/versioning.md).
42+
Both forms of extension methods generate the same intermediate language (IL). Callers can't make a distinction between them. In fact, you can convert existing extension methods to the new member syntax without a breaking change. The formats are both binary and source compatible.
13443

13544
## See also
13645

137-
- [Parallel Programming Samples (these include many example extension methods)](/samples/browse/?products=dotnet&term=parallel)
138-
- [Lambda Expressions](../../language-reference/operators/lambda-expressions.md)
139-
- [Standard Query Operators Overview](../../linq/standard-query-operators/index.md)
140-
- [Conversion rules for Instance parameters and their impact](/archive/blogs/sreekarc/conversion-rules-for-instance-parameters-and-their-impact)
141-
- [Extension methods Interoperability between languages](/archive/blogs/sreekarc/extension-methods-interoperability-between-languages)
142-
- [Extension methods and Curried Delegates](/archive/blogs/sreekarc/extension-methods-and-curried-delegates)
143-
- [Extension method Binding and Error reporting](/archive/blogs/sreekarc/extension-method-binding-and-error-reporting)
144-
46+
- [Extensions feature specification](~/_csharplang/proposals/extensions.md)
14547

14648
## C# language specification
14749

14850
[!INCLUDE[CSharplangspec](~/includes/csharplangspec-md.md)]
149-
150-
## See also
151-
152-
- [Extension methods](./this.md#extension-method-declarations)
153-
- <xref:System.Runtime.InteropServices.DllImportAttribute?displayProperty=nameWithType>
154-
- [C# Keywords](index.md)
155-
- [Modifiers](index.md)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
5+
namespace keywords_ExtensionMethods;
6+
7+
// <ExtensionMethod>
8+
public static class NumericSequenceExtensionMethods
9+
{
10+
public static IEnumerable<int> Add(this IEnumerable<int> sequence, int operand)
11+
{
12+
foreach (var item in sequence)
13+
yield return item + operand;
14+
}
15+
}
16+
// </ExtensionMethod>
17+
18+
public static class ExtensionExamples
19+
{
20+
public static void BasicExample()
21+
{
22+
// <UseExtensionMethod>
23+
IEnumerable<int> numbers = Enumerable.Range(1, 10);
24+
numbers = numbers.Add(10);
25+
// </UseExtensionMethod>
26+
}
27+
}
28+
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,76 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Text;
1+
namespace keywords;
42

5-
namespace keywords;
6-
internal class Extensions
3+
// <ExtensionMembers>
4+
public static class NumericSequences
75
{
6+
extension(IEnumerable<int> sequence)
7+
{
8+
public IEnumerable<int> Add(int operand)
9+
{
10+
foreach (var item in sequence)
11+
{
12+
yield return item + operand;
13+
}
14+
}
15+
16+
public int Median
17+
{
18+
get
19+
{
20+
21+
var sortedList = sequence.OrderBy(n => n).ToList();
22+
int count = sortedList.Count;
23+
int middleIndex = count / 2;
24+
25+
if (count % 2 == 0)
26+
{
27+
// Even number of elements: average the two middle elements
28+
return (sortedList[middleIndex - 1] + sortedList[middleIndex]);
29+
}
30+
else
31+
{
32+
// Odd number of elements: return the middle element
33+
return sortedList[middleIndex];
34+
}
35+
}
36+
}
37+
38+
public int this[int index] => sequence.Skip(index).First();
39+
}
40+
}
41+
// </ExtensionMembers>
42+
43+
public static class NumericStaticExtensions
44+
{
45+
// <StaticExtensions>
46+
extension(IEnumerable<int>)
47+
{
48+
// Method:
49+
public static IEnumerable<int> Generate(int low, int count, int increment)
50+
{
51+
for (int i = 0; i < count; i++)
52+
yield return low + (i * increment);
53+
}
54+
55+
// Property:
56+
public static IEnumerable<int> Identity => Enumerable.Empty<int>();
57+
}
58+
// </StaticExtensions>
59+
}
60+
61+
public static class ExtensionExamples
62+
{
63+
public static void BasicExample()
64+
{
65+
// <UseExtensionMethod>
66+
IEnumerable<int> numbers = Enumerable.Range(1, 10);
67+
numbers = numbers.Add(10);
68+
69+
var median = numbers.Median;
70+
// </UseExtensionMethod>
71+
72+
// <UseStaticExtensions>
73+
var newSequence = IEnumerable<int>.Generate(5, 10, 2);
74+
var identity = IEnumerable<int>.Identity;
75+
}
876
}

0 commit comments

Comments
 (0)