diff --git a/.openpublishing.redirection.csharp.json b/.openpublishing.redirection.csharp.json index 2275630efad74..94e4a4be52400 100644 --- a/.openpublishing.redirection.csharp.json +++ b/.openpublishing.redirection.csharp.json @@ -5068,6 +5068,10 @@ "source_path_from_root": "/docs/csharp/programming-guide/statements-expressions-operators/default-value-expressions.md", "redirect_url": "/dotnet/csharp/language-reference/operators/default" }, + { + "source_path_from_root": "/docs/csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md", + "redirect_url": "/dotnet/csharp/language-reference/operators/lambda-operator#expression-body-definition" + }, { "source_path_from_root": "/docs/csharp/programming-guide/statements-expressions-operators/expressions.md", "redirect_url": "/dotnet/csharp/language-reference/operators/index" @@ -5090,7 +5094,7 @@ }, { "source_path_from_root": "/docs/csharp/programming-guide/statements-expressions-operators/index.md", - "redirect_url": "/dotnet/csharp/programming-guide/statements-expressions-operators/statements" + "redirect_url": "/dotnet/csharp/fundamentals/statements" }, { "source_path_from_root": "/docs/csharp/programming-guide/statements-expressions-operators/lambda-expressions.md", @@ -5104,6 +5108,10 @@ "source_path_from_root": "/docs/csharp/programming-guide/statements-expressions-operators/overloadable-operators.md", "redirect_url": "/dotnet/csharp/language-reference/operators/operator-overloading#overloadable-operators" }, + { + "source_path_from_root": "/docs/csharp/programming-guide/statements-expressions-operators/statements.md", + "redirect_url": "/dotnet/csharp/fundamentals/statements" + }, { "source_path_from_root": "/docs/csharp/programming-guide/statements-expressions-operators/using-conversion-operators.md", "redirect_url": "/dotnet/csharp/language-reference/operators/user-defined-conversion-operators" diff --git a/docs/csharp/fundamentals/null-safety/null-operators.md b/docs/csharp/fundamentals/null-safety/null-operators.md index c485629fdc545..480527f453ac0 100644 --- a/docs/csharp/fundamentals/null-safety/null-operators.md +++ b/docs/csharp/fundamentals/null-safety/null-operators.md @@ -99,6 +99,10 @@ Use `!` sparingly, and only when you have information the compiler doesn't. Exam ## See also + + - [Null safety overview](index.md) - [Nullable value types](nullable-value-types.md) - [Nullable reference types](nullable-reference-types.md) diff --git a/docs/csharp/fundamentals/program-structure/index.md b/docs/csharp/fundamentals/program-structure/index.md index 9ea76be5d2f34..865595351061f 100644 --- a/docs/csharp/fundamentals/program-structure/index.md +++ b/docs/csharp/fundamentals/program-structure/index.md @@ -110,7 +110,7 @@ Statements often contain expressions, and expressions can nest inside other expr var maxResult = Math.Max(a, b) + Math.Max(c, d); ``` -For detailed information about statements, see [Statements](../../programming-guide/statements-expressions-operators/statements.md). For information about expression-bodied members, see [Expression-bodied members](../../programming-guide/statements-expressions-operators/expression-bodied-members.md). +For detailed information about statements, see [Statements](../statements/index.md). For information about expression-bodied members, see [Expression body definitions](../../language-reference/operators/lambda-operator.md#expression-body-definition). ## Related content diff --git a/docs/csharp/fundamentals/statements/index.md b/docs/csharp/fundamentals/statements/index.md new file mode 100644 index 0000000000000..369194800ace8 --- /dev/null +++ b/docs/csharp/fundamentals/statements/index.md @@ -0,0 +1,105 @@ +--- +title: "C# statements" +description: Learn how C# statements declare variables, perform actions, group code into blocks, and control the flow of execution. +ms.date: 08/20/2026 +ms.topic: concept-article +ai-usage: ai-assisted +--- + +# C# statements + +> [!TIP] +> This article is part of the **Fundamentals** section for developers who already know at least one programming language and are learning C#. If you're new to programming, start with the [Get started](../../tour-of-csharp/tutorials/index.md) tutorials first. For complete statement syntax, see [Statements](~/_csharpstandard/standard/statements.md) in the C# language specification. +> +> **Coming from another language?** Declarations, conditions, loops, and returns might be familiar. C# uses its own syntax and classification for these features, which this article introduces. + +A *statement* is a complete command: "do this." Together, the statements in a program form a recipe that the program follows from start to finish. Most statements run in sequence. Branches choose which steps to run, and loops repeat steps. + +This example declares a quantity, displays it, and then uses an `if` statement to decide whether to restock: + +:::code language="csharp" source="./snippets/statements-overview/Program.cs" id="StatementRecipe"::: + +Read the example as complete commands before looking at their parts. The declaration, the first call to `Console.WriteLine`, the entire `if` construct, and the final call to `Console.WriteLine` are statements. The block inside the `if` statement contains two more statements. + +## Statements often contain expressions + +Statements often contain *expressions*, which are pieces of code that produce values. In the preceding example, the whole `if` construct is a statement. Its condition, `quantity < 10`, is an expression that produces either `true` or `false`. + +A *declaration statement* introduces a local variable or constant. An initializer expression can provide its first value: + +```csharp +int quantity = 5; +``` + +The complete line is a declaration statement. The initializer `5` is an expression within that statement. A declaration isn't an expression, so you can't place a declaration where C# expects a value. + +An *assignment expression* stores a value in a variable, property, indexer, or other storage location. C# permits an assignment expression to form an *expression statement*: + +```csharp +quantity = 10; +``` + +This statement performs an action rather than merely calculating a value. Method calls and increment operations are other common expression statements: + +```csharp +Console.WriteLine("Restocking"); +quantity++; +``` + +Only the following expression forms can be expression statements: + +- Assignment expressions +- Method invocation expressions +- Object creation expressions +- Prefix or postfix increment and decrement expressions +- `await` expressions + +Not every expression can stand alone as a statement. For example, `quantity + 1;` computes a value but doesn't use it, so the compiler reports [Compiler Error CS0201](../../language-reference/compiler-messages/cs0201.md). + + + +## Group statements in blocks + +A *block* groups zero or more statements between braces (`{` and `}`). C# treats the group as one statement. In the opening example, the `if` statement can run both the assignment and the call to `Console.WriteLine` because a block groups them into one body. Blocks can nest inside other blocks. + +Selection and iteration statements call their body an *embedded statement*. That body can be one statement without braces or a block that groups multiple statements. + +Prefer a block even when a body contains only one statement. Braces show which statements belong to the body and prevent later edits from accidentally placing a statement outside it. + +### Blocks and variable scope + +Variables declared in a block are in scope from their declaration through the end of that block. A nested block can use variables declared by an enclosing block, but the enclosing block can't use variables declared only in the nested block: + +:::code language="csharp" source="./snippets/statements-overview/Program.cs" id="BlocksAndScope"::: + +## Choose a statement for the task + +After you recognize statements as commands, you can choose among their different kinds by purpose: + +- **Declare data:** [Declaration statements](../../language-reference/statements/declarations.md) introduce local variables and constants. +- **Perform actions:** Expression statements assign values, call methods, create objects, increment or decrement values, or await asynchronous operations. +- **Choose steps:** [Selection statements](selection.md), such as `if` and `switch`, choose which code runs. +- **Repeat steps:** [Iteration statements](iteration.md), such as `foreach`, `while`, and `for`, repeat a statement or block. +- **Transfer control:** [Jump statements](../../language-reference/statements/jump-statements.md), such as `break`, `continue`, `return`, and `yield`, move execution to another point. +- **Handle exceptions:** [Exception-handling statements](../../language-reference/statements/exception-handling-statements.md), such as `try`, `catch`, and `throw`, respond to or report errors. +- **Manage resources:** The [`using` statement](../../language-reference/statements/using.md) ensures that resources are disposed. +- **Use specialized behavior:** The [`checked` and `unchecked`](../../language-reference/statements/checked-and-unchecked.md), [`fixed`](../../language-reference/statements/fixed.md), and [`lock`](../../language-reference/statements/lock.md) statements support specific scenarios. + +## Less common statements + +The *empty statement* is a lone semicolon: + +```csharp +; +``` + +It performs no action. An empty statement is legal where C# expects a statement, but a stray semicolon after an `if`, `while`, or `for` can create an empty body and cause unexpected behavior. Use an empty statement only when the no-op is intentional and clear. + +## C# language specification + +For more information, see the [Statements](~/_csharpstandard/standard/statements.md) section of the [C# language specification](~/_csharpstandard/standard/README.md). + +## See also + +- [Statement keywords](../../language-reference/keywords/statement-keywords.md) +- [C# operators and expressions](../../language-reference/operators/index.md) diff --git a/docs/csharp/fundamentals/statements/snippets/statements-overview/Program.cs b/docs/csharp/fundamentals/statements/snippets/statements-overview/Program.cs new file mode 100644 index 0000000000000..3786c7a370b94 --- /dev/null +++ b/docs/csharp/fundamentals/statements/snippets/statements-overview/Program.cs @@ -0,0 +1,41 @@ +namespace StatementsOverview; + +public static class Program +{ + public static void Main() + { + ShowStatementRecipe(); + ShowBlocksAndScope(); + } + + private static void ShowStatementRecipe() + { + // + int quantity = 5; + Console.WriteLine($"Quantity: {quantity}"); // => Quantity: 5 + + if (quantity < 10) + { + quantity = 10; + Console.WriteLine("Restocked"); // => Restocked + } + + Console.WriteLine($"Quantity: {quantity}"); // => Quantity: 10 + // + } + + private static void ShowBlocksAndScope() + { + // + int outerValue = 10; + + if (outerValue > 0) + { + int innerValue = outerValue * 2; + Console.WriteLine(innerValue); // => 20 + } + + // innerValue isn't in scope here. + // + } +} diff --git a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/ExpressionBodiedMembers.csproj b/docs/csharp/fundamentals/statements/snippets/statements-overview/statements-overview.csproj similarity index 64% rename from samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/ExpressionBodiedMembers.csproj rename to docs/csharp/fundamentals/statements/snippets/statements-overview/statements-overview.csproj index 2150e3797ba5e..bad583f080c8c 100644 --- a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/ExpressionBodiedMembers.csproj +++ b/docs/csharp/fundamentals/statements/snippets/statements-overview/statements-overview.csproj @@ -1,10 +1,8 @@ - - + Exe - net8.0 - enable + net10.0 enable + enable - diff --git a/docs/csharp/fundamentals/tutorials/nullable-reference-types.md b/docs/csharp/fundamentals/tutorials/nullable-reference-types.md index 0f0e7cc57a949..fdc531badb07a 100644 --- a/docs/csharp/fundamentals/tutorials/nullable-reference-types.md +++ b/docs/csharp/fundamentals/tutorials/nullable-reference-types.md @@ -145,7 +145,7 @@ Call `PerformSurvey` from `Main`: ## Examine the survey results -To report results, expose a few helpers from `SurveyResponse` and `SurveyRun`. On `SurveyResponse`, add [expression-bodied members](../../programming-guide/statements-expressions-operators/expression-bodied-members.md) (members defined with `=>` and a single expression instead of a `{ ... }` block) that handle the nullable dictionary: +To report results, expose a few helpers from `SurveyResponse` and `SurveyRun`. On `SurveyResponse`, add [expression-bodied members](../../language-reference/operators/lambda-operator.md#expression-body-definition) (members defined with `=>` and a single expression instead of a `{ ... }` block) that handle the nullable dictionary: :::code language="csharp" source="snippets/NullableIntroduction/SurveyResponse.cs" id="SnippetSurveyStatus"::: diff --git a/docs/csharp/fundamentals/types/built-in-types.md b/docs/csharp/fundamentals/types/built-in-types.md index 8a717b9809e29..e9c88979de5dc 100644 --- a/docs/csharp/fundamentals/types/built-in-types.md +++ b/docs/csharp/fundamentals/types/built-in-types.md @@ -124,6 +124,10 @@ Use `dynamic` when interacting with COM APIs, dynamic languages, or reflection-h ## See also + + - [Type system overview](index.md) - [Built-in types (C# reference)](../../language-reference/builtin-types/built-in-types.md) - [Integral numeric types](../../language-reference/builtin-types/integral-numeric-types.md) diff --git a/docs/csharp/language-reference/compiler-messages/cs0201.md b/docs/csharp/language-reference/compiler-messages/cs0201.md index 96988e63894da..3e72ba0eadbe0 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0201.md +++ b/docs/csharp/language-reference/compiler-messages/cs0201.md @@ -12,7 +12,7 @@ ms.assetid: cf5d6701-50cc-4e4f-878b-e1a4ad8a2061 Only assignment, call, increment, decrement, and new object expressions can be used as a statement - The compiler generates an error when it encounters an invalid statement. An invalid statement is any line or series of lines ending in a semicolon that does not represent an assignment ([=](../operators/assignment-operator.md)), method call [()](../operators/member-access-operators.md#invocation-expression-), [new](../operators/new-operator.md), [--](../operators/arithmetic-operators.md#decrement-operator---) or [++](../operators/arithmetic-operators.md#increment-operator-) operation. For more information, see [Statements](../../programming-guide/statements-expressions-operators/statements.md) and [Operators and expressions](../operators/index.md). + The compiler generates an error when it encounters an invalid statement. An invalid statement is any line or series of lines ending in a semicolon that does not represent an assignment ([=](../operators/assignment-operator.md)), method call [()](../operators/member-access-operators.md#invocation-expression-), [new](../operators/new-operator.md), [--](../operators/arithmetic-operators.md#decrement-operator---) or [++](../operators/arithmetic-operators.md#increment-operator-) operation. For more information, see [Statements](../../fundamentals/statements/index.md) and [Operators and expressions](../operators/index.md). ## Example 1 diff --git a/docs/csharp/language-reference/keywords/statement-keywords.md b/docs/csharp/language-reference/keywords/statement-keywords.md index 71efd51f09145..b7749ee95b84c 100644 --- a/docs/csharp/language-reference/keywords/statement-keywords.md +++ b/docs/csharp/language-reference/keywords/statement-keywords.md @@ -8,7 +8,7 @@ helpviewer_keywords: --- # Statement keywords (C# Reference) -Statements are program instructions. Except as described in the topics referenced in the following list, the program executes statements in sequence. The following list shows the C# statement keywords. For more information about statements that don't use a keyword, see [Statements](../../programming-guide/statements-expressions-operators/statements.md). +Statements are program instructions. Except as described in the topics referenced in the following list, the program executes statements in sequence. The following list shows the C# statement keywords. For more information about statements that don't use a keyword, see [Statements](../../fundamentals/statements/index.md). - [Selection statements](../statements/selection-statements.md) - `if` @@ -40,5 +40,5 @@ Statements are program instructions. Except as described in the topics reference ## See also -- [Statements](../../programming-guide/statements-expressions-operators/statements.md) +- [Statements](../../fundamentals/statements/index.md) - [C# Keywords](index.md) diff --git a/docs/csharp/language-reference/operators/default.md b/docs/csharp/language-reference/operators/default.md index 1dbfc5350001d..6c2052ab30af7 100644 --- a/docs/csharp/language-reference/operators/default.md +++ b/docs/csharp/language-reference/operators/default.md @@ -28,7 +28,7 @@ You can use the `default` literal to produce the default value of a type when th - In the assignment or initialization of a variable. - In the declaration of the default value for an [optional method parameter](../../methods.md#optional-parameters-and-arguments). - In a method call to provide an argument value. -- In a [`return` statement](../statements/jump-statements.md#the-return-statement) or as an expression in an [expression-bodied member](../../programming-guide/statements-expressions-operators/expression-bodied-members.md). +- In a [`return` statement](../statements/jump-statements.md#the-return-statement) or as an expression in an [expression-bodied member](lambda-operator.md#expression-body-definition). The following example shows the usage of the `default` literal: diff --git a/docs/csharp/language-reference/operators/index.md b/docs/csharp/language-reference/operators/index.md index 7fff6d38ca72a..9042b711779f0 100644 --- a/docs/csharp/language-reference/operators/index.md +++ b/docs/csharp/language-reference/operators/index.md @@ -32,7 +32,7 @@ In the following code, examples of expressions appear on the right-hand side of :::code language="csharp" source="snippets/shared/Overview.cs" id="Expressions"::: -Typically, an expression produces a result and can be included in another expression. A [`void`](../builtin-types/void.md) method call is an example of an expression that doesn't produce a result. It can be used only as a [statement](../../programming-guide/statements-expressions-operators/statements.md), as the following example shows: +Typically, an expression produces a result and can be included in another expression. A [`void`](../builtin-types/void.md) method call is an example of an expression that doesn't produce a result. It can be used only as a [statement](../../fundamentals/statements/index.md), as the following example shows: ```csharp Console.WriteLine("Hello, world!"); @@ -52,7 +52,7 @@ Here are some other kinds of expressions that C# provides: :::code language="csharp" source="snippets/shared/Overview.cs" id="Query"::: -You can use an [expression body definition](../../programming-guide/statements-expressions-operators/expression-bodied-members.md) to provide a concise definition for a method, constructor, property, indexer, or finalizer. +You can use an [expression body definition](lambda-operator.md#expression-body-definition) to provide a concise definition for a method, constructor, property, indexer, or finalizer. ## Operator precedence diff --git a/docs/csharp/language-reference/operators/lambda-operator.md b/docs/csharp/language-reference/operators/lambda-operator.md index 57faf7ac0c3b6..d79a2a58bfb5a 100644 --- a/docs/csharp/language-reference/operators/lambda-operator.md +++ b/docs/csharp/language-reference/operators/lambda-operator.md @@ -1,7 +1,8 @@ --- title: "The lambda operator - The `=>` operator is used to define a lambda expression" description: "The C# => operator defines lambda expressions and expression bodied members. Lambda expressions define a block of code used as data." -ms.date: 01/20/2026 +ms.date: 08/20/2026 +ai-usage: ai-assisted f1_keywords: - "=>_CSharpKeyword" helpviewer_keywords: @@ -41,15 +42,7 @@ An expression body definition uses the following general syntax: member => expression; ``` -The `expression` is a valid expression. The return type of `expression` must be implicitly convertible to the member's return type. If the member: - -- Has a `void` return type, or -- Is a: - - Constructor - - Finalizer - - Property or indexer `set` accessor - -`expression` must be a [*statement expression*](~/_csharpstandard/standard/statements.md#137-expression-statements). Because the expression's result is discarded, the return type of that expression can be any type. +For a member that returns a value, the expression's result must be implicitly convertible to the member's return type. For a `void` member, constructor, finalizer, or `set`, `init`, `add`, or `remove` accessor, the body must be a [*statement expression*](~/_csharpstandard/standard/statements.md#137-expression-statements). A statement expression can be an assignment, method invocation, object creation, increment or decrement operation, or `await` expression. Its result, if any, is discarded. The following example shows an expression body definition for a `Person.ToString` method: @@ -66,7 +59,13 @@ public override string ToString() } ``` -You can create expression body definitions for methods, operators, read-only properties, constructors, finalizers, and property and indexer accessors. For more information, see [Expression-bodied members](../../programming-guide/statements-expressions-operators/expression-bodied-members.md). +You can use expression body definitions for the following members: + +- **Methods and local functions:** A member that returns a value has the form `T M() => expression;`. A `void` member has the form `void M() => statementExpression;`. For more information, see [Methods](../../programming-guide/classes-and-structs/methods.md) and [Local functions](../../programming-guide/classes-and-structs/local-functions.md). +- **Operators:** An operator has the form `public static T operator +(T left, T right) => expression;`. For more information, see [Operator overloading](operator-overloading.md). +- **Properties and indexers:** A read-only property or indexer has the form `T P => expression;` or `T this[int i] => expression;`. You can also use expression bodies for individual accessors. A `get` accessor has the form `get => expression;`. A `set` or `init` accessor has the form `set => statementExpression;` or `init => statementExpression;`. For more information, see [Properties](../../programming-guide/classes-and-structs/properties.md) and [Indexers](../../programming-guide/indexers/index.md). +- **Constructors and finalizers:** These members have the form `C() => statementExpression;` or `~C() => statementExpression;`. For more information, see [Constructors](../../programming-guide/classes-and-structs/constructors.md) and [Finalizers](../../programming-guide/classes-and-structs/finalizers.md). +- **Event accessors:** An `add` or `remove` accessor has the form `add => statementExpression;` or `remove => statementExpression;`. For more information, see [Events](../../programming-guide/events/index.md). ## Operator overloadability diff --git a/docs/csharp/language-reference/operators/null-coalescing-operator.md b/docs/csharp/language-reference/operators/null-coalescing-operator.md index e3dd1c648d671..41776c0bc33f0 100644 --- a/docs/csharp/language-reference/operators/null-coalescing-operator.md +++ b/docs/csharp/language-reference/operators/null-coalescing-operator.md @@ -57,7 +57,7 @@ The `??` and `??=` operators are useful in the following scenarios: :::code language="csharp" source="snippets/shared/NullCoalescingOperator.cs" id="WithThrowExpression"::: - The preceding example also demonstrates how to use [expression-bodied members](../../programming-guide/statements-expressions-operators/expression-bodied-members.md) to define a property. + The preceding example also demonstrates how to use [expression-bodied members](lambda-operator.md#expression-body-definition) to define a property. - Use the `??=` operator to replace code of the following form: diff --git a/docs/csharp/language-reference/statements/selection-statements.md b/docs/csharp/language-reference/statements/selection-statements.md index db4e1b4ba1869..0de63a76555a1 100644 --- a/docs/csharp/language-reference/statements/selection-statements.md +++ b/docs/csharp/language-reference/statements/selection-statements.md @@ -77,7 +77,7 @@ In an expression context, you can use the [`switch` expression](../operators/swi > Differences between **switch expression** and **switch statement**: > > - **switch statement** is used to control the execution flow within a block of code. -> - **switch expression** is typically used in contexts of value return and value assignment, often as [expression-bodied members](../../programming-guide/statements-expressions-operators/expression-bodied-members.md). +> - **switch expression** is typically used in contexts of value return and value assignment, often as [expression-bodied members](../operators/lambda-operator.md#expression-body-definition). > - a **switch expression** case section can't be empty, but a **switch statement** case section can. ### Case guards diff --git a/docs/csharp/misc/cs1002.md b/docs/csharp/misc/cs1002.md index 4acbb699f5647..60fbeb3a0880e 100644 --- a/docs/csharp/misc/cs1002.md +++ b/docs/csharp/misc/cs1002.md @@ -1,18 +1,19 @@ --- description: "Compiler Error CS1002" title: "Compiler Error CS1002" -ms.date: 07/20/2015 +ms.date: 08/20/2026 f1_keywords: - "CS1002" helpviewer_keywords: - "CS1002" ms.assetid: 659b7abf-9311-40c9-9594-5372464c6148 +ai-usage: ai-assisted --- # Compiler Error CS1002 ; expected - The compiler detected a missing semicolon. A semicolon is required at the end of every statement in C#. A statement may span more than one line. + The compiler detected a missing semicolon. A semicolon terminates many C# statements, including declarations, assignments, expression statements, and `return` statements. Blocks and control statements such as `if`, `for`, and `while` don't end with a semicolon. A statement can span more than one line. The following sample generates CS1002: @@ -34,4 +35,4 @@ namespace x ## See also -- [Statements](../programming-guide/statements-expressions-operators/statements.md) +- [Statements](../fundamentals/statements/index.md) diff --git a/docs/csharp/programming-guide/classes-and-structs/constructors.md b/docs/csharp/programming-guide/classes-and-structs/constructors.md index 3c4273a08d237..e03c9b64e894f 100644 --- a/docs/csharp/programming-guide/classes-and-structs/constructors.md +++ b/docs/csharp/programming-guide/classes-and-structs/constructors.md @@ -32,7 +32,7 @@ A constructor is a method with the same name as its type. Its method signature c :::code source="./snippets/constructors/Program.cs" id="InstanceCtor"::: -If a constructor can be implemented as a single statement, you can use an [expression body member](../statements-expressions-operators/expression-bodied-members.md). The following example defines a `Location` class whose constructor has a single string parameter, `name`. The expression body definition assigns the argument to the `locationName` field. +If a constructor can be implemented as a single statement, you can use an [expression body member](../../language-reference/operators/lambda-operator.md#expression-body-definition). The following example defines a `Location` class whose constructor has a single string parameter, `name`. The expression body definition assigns the argument to the `locationName` field. :::code source="./snippets/constructors/Program.cs" id="ExpressionBodiedCtor"::: diff --git a/docs/csharp/programming-guide/statements-expressions-operators/equality-comparisons.md b/docs/csharp/programming-guide/statements-expressions-operators/equality-comparisons.md index 2f0c6a42cb514..48ee040e428d8 100644 --- a/docs/csharp/programming-guide/statements-expressions-operators/equality-comparisons.md +++ b/docs/csharp/programming-guide/statements-expressions-operators/equality-comparisons.md @@ -14,7 +14,7 @@ It is sometimes necessary to compare two values for equality. In some cases, you Reference equality means that two object references refer to the same underlying object. This can occur through simple assignment, as shown in the following example. - [!code-csharp[csProgGuideStatements#18](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs#18)] + :::code language="csharp" source="./snippets/equality-comparisons/Program.cs"::: In this code, two objects are created, but after the assignment statement, both references refer to the same object. Therefore they have reference equality. Use the method to determine whether two references refer to the same object. diff --git a/docs/csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md b/docs/csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md deleted file mode 100644 index 50539b28d58a4..0000000000000 --- a/docs/csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: "Expression-bodied members" -description: Learn about expression-bodied members. See code examples that use expression body definition for properties, constructors, finalizers, and more. -ms.date: 02/06/2019 -helpviewer_keywords: - - "expression-bodied members[C#]" - - "C# language, expression-bodied members" ---- -# Expression-bodied members (C# programming guide) - -Expression body definitions let you provide a member's implementation in a concise, readable form. You can use an expression body definition whenever the logic for any supported member, such as a method or property, consists of a single expression. An expression body definition has the following general syntax: - -```csharp -member => expression; -``` - -where *expression* is a valid expression. - -Expression body definitions can be used with the following type members: - -- [Method](#methods) -- [Read-only property](#read-only-properties) -- [Property](#properties) -- [Constructor](#constructors) -- [Finalizer](#finalizers) -- [Indexer](#indexers) - -## Methods - -An expression-bodied method consists of a single expression that returns a value whose type matches the method's return type, or, for methods that return `void`, that performs some operation. For example, types that override the method typically include a single expression that returns the string representation of the current object. - -The following example defines a `Person` class that overrides the method with an expression body definition. It also defines a `DisplayName` method that displays a name to the console. Additionally, it includes several methods that take parameters, demonstrating how expression-bodied members work with method parameters. The `return` keyword is not used in any of the expression body definitions. - -[!code-csharp[expression-bodied-methods](../../../../samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-methods.cs)] - -For more information, see [Methods (C# Programming Guide)](../classes-and-structs/methods.md). - -## Read-only properties - -You can use expression body definition to implement a read-only property. To do that, use the following syntax: - -```csharp -PropertyType PropertyName => expression; -``` - -The following example defines a `Location` class whose read-only `Name` property is implemented as an expression body definition that returns the value of the private `locationName` field: - -[!code-csharp[expression-bodied-read-only-property](../../../../samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-readonly.cs#1)] - -For more information about properties, see [Properties (C# Programming Guide)](../classes-and-structs/properties.md). - -## Properties - -You can use expression body definitions to implement property `get` and `set` accessors. The following example demonstrates how to do that: - -[!code-csharp[expression-bodied-property-get-set](../../../../samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-ctor.cs#1)] - -For more information about properties, see [Properties (C# Programming Guide)](../classes-and-structs/properties.md). - -## Events - -Similarly, event `add` and `remove` accessors can be expression-bodied: - -[!code-csharp[expression-bodied-event-add-remove](../../../../samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-event.cs#1)] - -For more information about events, see [Events (C# Programming Guide)](../events/index.md). - -## Constructors - -An expression body definition for a constructor typically consists of a single assignment expression or a method call that handles the constructor's arguments or initializes instance state. - -The following example defines a `Location` class whose constructor has a single string parameter named *name*. The expression body definition assigns the argument to the `Name` property. The example also shows a `Point` class with constructors that take multiple parameters, demonstrating how expression-bodied constructors work with different parameter combinations. - -[!code-csharp[expression-bodied-constructor](../../../../samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-ctor.cs#1)] - -For more information, see [Constructors (C# Programming Guide)](../classes-and-structs/constructors.md). - -## Finalizers - -An expression body definition for a finalizer typically contains cleanup statements, such as statements that release unmanaged resources. - -The following example defines a finalizer that uses an expression body definition to indicate that the finalizer has been called. - -[!code-csharp[expression-bodied-finalizer](../classes-and-structs/snippets/finalizers/expr-bodied-finalizer.cs#1)] - -For more information, see [Finalizers (C# Programming Guide)](../classes-and-structs/finalizers.md). - -## Indexers - -Like with properties, indexer `get` and `set` accessors consist of expression body definitions if the `get` accessor consists of a single expression that returns a value or the `set` accessor performs a simple assignment. - -The following example defines a class named `Sports` that includes an internal array that contains the names of some sports. Both the indexer `get` and `set` accessors are implemented as expression body definitions. - -[!code-csharp[expression-bodied-indexer](../../../../samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-indexers.cs#1)] - -For more information, see [Indexers (C# Programming Guide)](../indexers/index.md). - -## See also - -- [.NET code style rules for expression-bodied-members](../../../fundamentals/code-analysis/style-rules/language-rules.md#expression-bodied-members) diff --git a/docs/csharp/programming-guide/statements-expressions-operators/snippets/equality-comparisons/Program.cs b/docs/csharp/programming-guide/statements-expressions-operators/snippets/equality-comparisons/Program.cs new file mode 100644 index 0000000000000..7077333e3c014 --- /dev/null +++ b/docs/csharp/programming-guide/statements-expressions-operators/snippets/equality-comparisons/Program.cs @@ -0,0 +1,22 @@ +namespace EqualityComparisons; + +public static class Program +{ + public static void Main() + { + var first = new Sample { Number = 1, Text = "Hi" }; + var second = new Sample { Number = 1, Text = "Hi" }; + + Console.WriteLine(ReferenceEquals(first, second)); // => False + + second = first; + + Console.WriteLine(ReferenceEquals(first, second)); // => True + } + + private sealed class Sample + { + public int Number { get; init; } + public required string Text { get; init; } + } +} diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.csproj b/docs/csharp/programming-guide/statements-expressions-operators/snippets/equality-comparisons/equality-comparisons.csproj similarity index 55% rename from samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.csproj rename to docs/csharp/programming-guide/statements-expressions-operators/snippets/equality-comparisons/equality-comparisons.csproj index a150dcce740be..bad583f080c8c 100644 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.csproj +++ b/docs/csharp/programming-guide/statements-expressions-operators/snippets/equality-comparisons/equality-comparisons.csproj @@ -1,11 +1,8 @@ - - + Exe - net8.0 - enable + net10.0 enable - Program + enable - diff --git a/docs/csharp/programming-guide/statements-expressions-operators/statements.md b/docs/csharp/programming-guide/statements-expressions-operators/statements.md deleted file mode 100644 index f264ad71d6b0a..0000000000000 --- a/docs/csharp/programming-guide/statements-expressions-operators/statements.md +++ /dev/null @@ -1,89 +0,0 @@ ---- -title: "Statements" -description: Learn about statements in C# programming. See a list of statement types, and view code examples and additional resources. -ms.date: 07/20/2015 -helpviewer_keywords: - - "statements [C#], about statements" - - "C# language, statements" -ms.assetid: 901bcde7-87de-4e15-833c-f9cfd40c8ce3 ---- -# Statements (C# Programming Guide) - -The actions that a program takes are expressed in statements. Common actions include declaring variables, assigning values, calling methods, looping through collections, and branching to one or another block of code, depending on a given condition. The order in which statements are executed in a program is called the flow of control or flow of execution. The flow of control may vary every time that a program is run, depending on how the program reacts to input that it receives at run time. - -A statement can consist of a single line of code that ends in a semicolon, or a series of single-line statements in a block. A statement block is enclosed in {} brackets and can contain nested blocks. The following code shows two examples of single-line statements, and a multi-line statement block: - -[!code-csharp[csProgGuideStatements#1](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs#1)] - -## Types of statements - -The following table lists the various types of statements in C# and their associated keywords, with links to topics that include more information: - -|Category|C# keywords / notes| -|--------------|---------------------------| -|[Declaration statements](#declaration-statements)|A declaration statement introduces a new variable or constant. A variable declaration can optionally assign a value to the variable. In a constant declaration, the assignment is required.| -|[Expression statements](#expression-statements)|Expression statements that calculate a value must store the value in a variable.| -|Selection statements|Selection statements enable you to branch to different sections of code, depending on one or more specified conditions. For more information, see the following topics:
  • [if](../../language-reference/statements/selection-statements.md#the-if-statement)
  • [switch](../../language-reference/statements/selection-statements.md#the-switch-statement)
| -|Iteration statements|Iteration statements enable you to loop through collections like arrays, or perform the same set of statements repeatedly until a specified condition is met. For more information, see the following topics:
  • [do](../../language-reference/statements/iteration-statements.md#the-do-statement)
  • [for](../../language-reference/statements/iteration-statements.md#the-for-statement)
  • [foreach](../../language-reference/statements/iteration-statements.md#the-foreach-statement)
  • [while](../../language-reference/statements/iteration-statements.md#the-while-statement)
| -|Jump statements|Jump statements transfer control to another section of code. For more information, see the following topics:
  • [break](../../language-reference/statements/jump-statements.md#the-break-statement)
  • [continue](../../language-reference/statements/jump-statements.md#the-continue-statement)
  • [goto](../../language-reference/statements/jump-statements.md#the-goto-statement)
  • [return](../../language-reference/statements/jump-statements.md#the-return-statement)
  • [yield](../../language-reference/statements/yield.md)
| -|Exception-handling statements|Exception-handling statements enable you to gracefully recover from exceptional conditions that occur at run time. For more information, see the following topics:
  • [throw](../../language-reference/statements/exception-handling-statements.md#the-throw-statement)
  • [try-catch](../../language-reference/statements/exception-handling-statements.md#the-try-catch-statement)
  • [try-finally](../../language-reference/statements/exception-handling-statements.md#the-try-finally-statement)
  • [try-catch-finally](../../language-reference/statements/exception-handling-statements.md#the-try-catch-finally-statement)
| -|[`checked` and `unchecked`](../../language-reference/statements/checked-and-unchecked.md)|The `checked` and `unchecked` statements enable you to specify whether integral-type numerical operations are allowed to cause an overflow when the result is stored in a variable that is too small to hold the resulting value.| -|The `await` statement|If you mark a method with the [async](../../language-reference/keywords/async.md) modifier, you can use the [await](../../language-reference/operators/await.md) operator in the method. When control reaches an `await` expression in the async method, control returns to the caller, and progress in the method is suspended until the awaited task completes. When the task is complete, execution can resume in the method.

For a simple example, see the "Async Methods" section of [Methods](../classes-and-structs/methods.md). For more information, see [Asynchronous Programming with async and await](../../asynchronous-programming/index.md).| -|The `yield return` statement|An iterator performs a custom iteration over a collection, such as a list or an array. An iterator uses the [yield return](../../language-reference/statements/yield.md) statement to return each element one at a time. When a `yield return` statement is reached, the current location in code is remembered. Execution is restarted from that location when the iterator is called the next time.

For more information, see [Iterators](../concepts/iterators.md).| -|The `fixed` statement|The fixed statement prevents the garbage collector from relocating a movable variable. For more information, see [fixed](../../language-reference/statements/fixed.md).| -|The `lock` statement|The lock statement enables you to limit access to blocks of code to only one thread at a time. For more information, see [lock](../../language-reference/statements/lock.md).| -|Labeled statements|You can give a statement a label and then use the [goto](../../language-reference/statements/jump-statements.md#the-goto-statement) keyword to jump to the labeled statement. (See the example in the following row.)| -|The [empty statement](#the-empty-statement)|The empty statement consists of a single semicolon. It does nothing and can be used in places where a statement is required but no action needs to be performed.| - -## Declaration statements - -The following code shows examples of variable declarations with and without an initial assignment, and a constant declaration with the necessary initialization. - -[!code-csharp[csProgGuideStatements#23](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs#23)] - -## Expression statements - -The following code shows examples of expression statements, including assignment, object creation with assignment, and method invocation. - -[!code-csharp[csProgGuideStatements#24](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs#24)] - -## The empty statement - -The following examples show two uses for an empty statement: - -[!code-csharp[csProgGuideStatements#25](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs#25)] - -## Embedded statements - -Some statements, for example, [iteration statements](../../language-reference/statements/iteration-statements.md), always have an embedded statement that follows them. This embedded statement may be either a single statement or multiple statements enclosed by {} brackets in a statement block. Even single-line embedded statements can be enclosed in {} brackets, as shown in the following example: - -[!code-csharp[csProgGuideStatements#26](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs#26)] - -An embedded statement that is not enclosed in {} brackets cannot be a declaration statement or a labeled statement. This is shown in the following example: - -[!code-csharp[csProgGuideStatements#27](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs#27)] - -Put the embedded statement in a block to fix the error: - -[!code-csharp[csProgGuideStatements#28](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs#28)] - -## Nested statement blocks - -Statement blocks can be nested, as shown in the following code: - -[!code-csharp[csProgGuideStatements#29](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs#29)] - -## Unreachable statements - -If the compiler determines that the flow of control can never reach a particular statement under any circumstances, it will produce warning CS0162, as shown in the following example: - -[!code-csharp[csProgGuideStatements#22](~/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs#22)] - -## C# language specification - -For more information, see the [Statements](~/_csharpstandard/standard/statements.md) section of the [C# language specification](~/_csharpstandard/standard/README.md). - -## See also - -- [Statement keywords](../../language-reference/keywords/statement-keywords.md) -- [C# operators and expressions](../../language-reference/operators/index.md) diff --git a/docs/csharp/toc.yml b/docs/csharp/toc.yml index 3e5ee8035ff78..3c4266ed2bf82 100644 --- a/docs/csharp/toc.yml +++ b/docs/csharp/toc.yml @@ -119,6 +119,8 @@ items: href: fundamentals/expressions/index.md - name: Equality href: fundamentals/expressions/equality.md + - name: Statements overview + href: fundamentals/statements/index.md - name: Selection statements href: fundamentals/statements/selection.md - name: Iteration statements @@ -535,20 +537,14 @@ items: href: programming-guide/concepts/covariance-contravariance/using-variance-for-func-and-action-generic-delegates.md - name: Iterators href: programming-guide/concepts/iterators.md - - name: Statements, expressions, and equality - items: - - name: Statements - href: programming-guide/statements-expressions-operators/statements.md - - name: Expression-bodied members - href: programming-guide/statements-expressions-operators/expression-bodied-members.md - - name: Equality and equality comparisons - items: - - name: Equality comparisons - href: programming-guide/statements-expressions-operators/equality-comparisons.md - - name: "How to define value equality for a type" - href: programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type.md - - name: "How to test for reference equality (identity)" - href: programming-guide/statements-expressions-operators/how-to-test-for-reference-equality-identity.md + - name: Equality and equality comparisons + items: + - name: Equality comparisons + href: programming-guide/statements-expressions-operators/equality-comparisons.md + - name: "How to define value equality for a type" + href: programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type.md + - name: "How to test for reference equality (identity)" + href: programming-guide/statements-expressions-operators/how-to-test-for-reference-equality-identity.md - name: Types items: - name: Casting and Type Conversions diff --git a/docs/csharp/whats-new/csharp-version-history.md b/docs/csharp/whats-new/csharp-version-history.md index 00e829b2edcf8..f17e20d4a66ef 100644 --- a/docs/csharp/whats-new/csharp-version-history.md +++ b/docs/csharp/whats-new/csharp-version-history.md @@ -305,7 +305,7 @@ C# version 7.0 was released with Visual Studio 2017. This version has some evolu - [Tuples and deconstruction](../language-reference/builtin-types/value-tuples.md) - [Pattern matching](../fundamentals/functional/pattern-matching.md) - [Local functions](../programming-guide/classes-and-structs/local-functions.md) -- [Expanded expression bodied members](../programming-guide/statements-expressions-operators/expression-bodied-members.md) +- [Expanded expression bodied members](../language-reference/operators/lambda-operator.md#expression-body-definition) - [Ref locals](../language-reference/statements/declarations.md#reference-variables) - [Ref returns](../language-reference/statements/jump-statements.md#ref-returns) @@ -442,7 +442,7 @@ The major features of C# 1.0 included: - [Properties](../programming-guide/classes-and-structs/properties.md) - [Delegates](../delegates-overview.md) - [Operators and expressions](../language-reference/operators/index.md) -- [Statements](../programming-guide/statements-expressions-operators/statements.md) +- [Statements](../fundamentals/statements/index.md) - [Attributes](/dotnet/csharp/advanced-topics/reflection-and-attributes) _Article_ [_originally published on the NDepend blog_](https://blog.ndepend.com/c-versions-look-language-history/)_, courtesy of Erik Dietrich and Patrick Smacchia._ diff --git a/docs/fundamentals/code-analysis/style-rules/ide0021.md b/docs/fundamentals/code-analysis/style-rules/ide0021.md index 6636c82ed34e7..ba7872e4eac5a 100644 --- a/docs/fundamentals/code-analysis/style-rules/ide0021.md +++ b/docs/fundamentals/code-analysis/style-rules/ide0021.md @@ -26,7 +26,7 @@ dev_langs: ## Overview -This style rule concerns the use of [expression bodies](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) versus block bodies for constructors. +This style rule concerns the use of [expression bodies](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) versus block bodies for constructors. ## Options @@ -80,6 +80,6 @@ For more information, see [How to suppress code analysis warnings](../suppress-w ## See also -- [Expression-bodied members](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) +- [Expression-bodied members](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) - [Code style language rules](language-rules.md) - [Code style rules reference](index.md) diff --git a/docs/fundamentals/code-analysis/style-rules/ide0022.md b/docs/fundamentals/code-analysis/style-rules/ide0022.md index c4943f87be289..af84a69b681ee 100644 --- a/docs/fundamentals/code-analysis/style-rules/ide0022.md +++ b/docs/fundamentals/code-analysis/style-rules/ide0022.md @@ -26,7 +26,7 @@ dev_langs: ## Overview -This style rule concerns the use of [expression bodies](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) versus block bodies for methods. +This style rule concerns the use of [expression bodies](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) versus block bodies for methods. ## Options @@ -80,6 +80,6 @@ For more information, see [How to suppress code analysis warnings](../suppress-w ## See also -- [Expression-bodied members](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) +- [Expression-bodied members](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) - [Code style language rules](language-rules.md) - [Code style rules reference](index.md) diff --git a/docs/fundamentals/code-analysis/style-rules/ide0023-ide0024.md b/docs/fundamentals/code-analysis/style-rules/ide0023-ide0024.md index fdf32c95ef43d..e4352489813e1 100644 --- a/docs/fundamentals/code-analysis/style-rules/ide0023-ide0024.md +++ b/docs/fundamentals/code-analysis/style-rules/ide0023-ide0024.md @@ -39,7 +39,7 @@ This article describes two related rules, `IDE0023` and `IDE0024`, which apply t ## Overview -This style rule concerns the use of [expression bodies](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) versus block bodies for operators. +This style rule concerns the use of [expression bodies](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) versus block bodies for operators. ## Options @@ -96,6 +96,6 @@ For more information, see [How to suppress code analysis warnings](../suppress-w ## See also -- [Expression-bodied members](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) +- [Expression-bodied members](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) - [Code style language rules](language-rules.md) - [Code style rules reference](index.md) diff --git a/docs/fundamentals/code-analysis/style-rules/ide0025.md b/docs/fundamentals/code-analysis/style-rules/ide0025.md index 7a1ffaac6507a..84deb50aa02de 100644 --- a/docs/fundamentals/code-analysis/style-rules/ide0025.md +++ b/docs/fundamentals/code-analysis/style-rules/ide0025.md @@ -26,7 +26,7 @@ dev_langs: ## Overview -This style rule concerns the use of [expression bodies](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) versus block bodies for properties. +This style rule concerns the use of [expression bodies](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) versus block bodies for properties. ## Options @@ -138,6 +138,6 @@ For more information, see [How to suppress code analysis warnings](../suppress-w ## See also -- [Expression-bodied members](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) +- [Expression-bodied members](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) - [Code style language rules](language-rules.md) - [Code style rules reference](index.md) diff --git a/docs/fundamentals/code-analysis/style-rules/ide0026.md b/docs/fundamentals/code-analysis/style-rules/ide0026.md index 11a7d8663e1a8..f1623c4a7c535 100644 --- a/docs/fundamentals/code-analysis/style-rules/ide0026.md +++ b/docs/fundamentals/code-analysis/style-rules/ide0026.md @@ -26,7 +26,7 @@ dev_langs: ## Overview -This style rule concerns the use of [expression bodies](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) versus block bodies for indexers. +This style rule concerns the use of [expression bodies](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) versus block bodies for indexers. ## Options @@ -80,6 +80,6 @@ For more information, see [How to suppress code analysis warnings](../suppress-w ## See also -- [Expression-bodied members](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) +- [Expression-bodied members](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) - [Code style language rules](language-rules.md) - [Code style rules reference](index.md) diff --git a/docs/fundamentals/code-analysis/style-rules/ide0027.md b/docs/fundamentals/code-analysis/style-rules/ide0027.md index 06e6e33990d58..bfebdd4f3373c 100644 --- a/docs/fundamentals/code-analysis/style-rules/ide0027.md +++ b/docs/fundamentals/code-analysis/style-rules/ide0027.md @@ -26,7 +26,7 @@ dev_langs: ## Overview -This style rule concerns the use of [expression bodies](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) versus block bodies for accessors. +This style rule concerns the use of [expression bodies](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) versus block bodies for accessors. ## Options @@ -84,6 +84,6 @@ For more information, see [How to suppress code analysis warnings](../suppress-w ## See also -- [Expression-bodied members](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) +- [Expression-bodied members](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) - [Code style language rules](language-rules.md) - [Code style rules reference](index.md) diff --git a/docs/fundamentals/code-analysis/style-rules/ide0053.md b/docs/fundamentals/code-analysis/style-rules/ide0053.md index 7e84fe3c2f0ab..def3b63d6ed38 100644 --- a/docs/fundamentals/code-analysis/style-rules/ide0053.md +++ b/docs/fundamentals/code-analysis/style-rules/ide0053.md @@ -26,7 +26,7 @@ dev_langs: ## Overview -This style rule concerns the use of [expression bodies](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) versus block bodies for [lambda expressions](../../../csharp/language-reference/operators/lambda-expressions.md). +This style rule concerns the use of [expression bodies](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) versus block bodies for [lambda expressions](../../../csharp/language-reference/operators/lambda-expressions.md). ## Options @@ -78,6 +78,6 @@ For more information, see [How to suppress code analysis warnings](../suppress-w ## See also -- [Expression-bodied members](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) +- [Expression-bodied members](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) - [Code style language rules](language-rules.md) - [Code style rules reference](index.md) diff --git a/docs/fundamentals/code-analysis/style-rules/ide0061.md b/docs/fundamentals/code-analysis/style-rules/ide0061.md index fec4444da6fee..e52beb636200b 100644 --- a/docs/fundamentals/code-analysis/style-rules/ide0061.md +++ b/docs/fundamentals/code-analysis/style-rules/ide0061.md @@ -26,7 +26,7 @@ dev_langs: ## Overview -This style rule concerns the use of [expression bodies](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) versus block bodies for [local functions](../../../csharp/programming-guide/classes-and-structs/local-functions.md). Local functions are private methods of a type that are nested in another member. +This style rule concerns the use of [expression bodies](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) versus block bodies for [local functions](../../../csharp/programming-guide/classes-and-structs/local-functions.md). Local functions are private methods of a type that are nested in another member. ## Options @@ -89,6 +89,6 @@ For more information, see [How to suppress code analysis warnings](../suppress-w ## See also -- [Expression-bodied members](../../../csharp/programming-guide/statements-expressions-operators/expression-bodied-members.md) +- [Expression-bodied members](../../../csharp/language-reference/operators/lambda-operator.md#expression-body-definition) - [Code style language rules](language-rules.md) - [Code style rules reference](index.md) diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Program.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Program.cs deleted file mode 100644 index 1dac0be4c1200..0000000000000 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Program.cs +++ /dev/null @@ -1,14 +0,0 @@ -using CsCsrefProgrammingStatements; - -internal class Program -{ - private static void Main(string[] args) - { - SimpleStatements.Main(); - WrapStatements.Main(); - CsCsrefProgrammingStatements.WrapGuidelines.Test.Main(); - CsCsrefProgrammingStatements.ValueEquality.Program.Main(); - CsCsrefProgrammingStatements.ValueEquality.Program.Main(); - CsCsrefProgrammingStatements.ValueEqualityValueTypes.Program.Main(); - } -} diff --git a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs b/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs deleted file mode 100644 index ef9652228ec6c..0000000000000 --- a/samples/snippets/csharp/VS_Snippets_VBCSharp/csProgGuideStatements/CS/Statements.cs +++ /dev/null @@ -1,638 +0,0 @@ -namespace CsCsrefProgrammingStatements -{ - //--------------------------------------------------------------------------- - public class SimpleStatements - { - // - public static void Main() - { - // Declaration statement. - int counter; - - // Assignment statement. - counter = 1; - - // Error! This is an expression, not an expression statement. - // counter + 1; - - // Declaration statements with initializers are functionally - // equivalent to declaration statement followed by assignment statement: - int[] radii = [15, 32, 108, 74, 9]; // Declare and initialize an array. - const double pi = 3.14159; // Declare and initialize constant. - - // foreach statement block that contains multiple statements. - foreach (int radius in radii) - { - // Declaration statement with initializer. - double circumference = pi * (2 * radius); - - // Expression statement (method invocation). A single-line - // statement can span multiple text lines because line breaks - // are treated as white space, which is ignored by the compiler. - System.Console.WriteLine($"Radius of circle #{counter} is {radius}. Circumference = {circumference:N2}"); - - // Expression statement (postfix increment). - counter++; - } // End of foreach statement block - } // End of Main method body. - } // End of SimpleStatements class. - /* - Output: - Radius of circle #1 = 15. Circumference = 94.25 - Radius of circle #2 = 32. Circumference = 201.06 - Radius of circle #3 = 108. Circumference = 678.58 - Radius of circle #4 = 74. Circumference = 464.96 - Radius of circle #5 = 9. Circumference = 56.55 - */ - // - public class WrapStatements - { - - public static void Main() - { - int x = 4; - bool b = ((x < 10) && (x > 5)) || ((x > 20) && (x < 25)); - bool b2 = 35 == System.Convert.ToInt32("35"); - } - - public static void test() - { - // - // Expression statements. - int i = 5; - string s = "Hello World"; - // - - System.Console.WriteLine(i.ToString()); - System.Console.WriteLine(s); - - // - int num = 5; - System.Console.WriteLine(num); // Output: 5 - num = 6; - System.Console.WriteLine(num); // Output: 6 - // - - int y = 0; - - // - y++; - // - - // - y = 2 + 3; - // - } - } - - //--------------------------------------------------------------------------- - namespace WrapGuidelines - { - // - using System; - class Test - { - public int Num { get; set; } - public string Str { get; set; } - - public static void Main() - { - Test a = new Test() { Num = 1, Str = "Hi" }; - Test b = new Test() { Num = 1, Str = "Hi" }; - - bool areEqual = System.Object.ReferenceEquals(a, b); - // False: - System.Console.WriteLine($"ReferenceEquals(a, b) = {areEqual}"); - - // Assign b to a. - b = a; - - // Repeat calls with different results. - areEqual = System.Object.ReferenceEquals(a, b); - // True: - System.Console.WriteLine($"ReferenceEquals(a, b) = {areEqual}"); - } - } - // - } - - // This is no longer in docs, replaced by ~docs\docs\csharp\programming-guide\statements-expressions-operators\snippets\how-to-define-value-equality-for-a-type\ValueEqualityClass\Program.cs - // - namespace ValueEquality - { - using System; - class TwoDPoint : IEquatable - { - // Readonly automatically implemented properties. - public int X { get; private set; } - public int Y { get; private set; } - - // Set the properties in the constructor. - public TwoDPoint(int x, int y) - { - if ((x < 1) || (x > 2000) || (y < 1) || (y > 2000)) - { - throw new System.ArgumentException("Point must be in range 1 - 2000"); - } - this.X = x; - this.Y = y; - } - - public override bool Equals(object obj) - { - return this.Equals(obj as TwoDPoint); - } - - public bool Equals(TwoDPoint p) - { - // If parameter is null, return false. - if (Object.ReferenceEquals(p, null)) - { - return false; - } - - // Optimization for a common success case. - if (Object.ReferenceEquals(this, p)) - { - return true; - } - - // If run-time types are not exactly the same, return false. - if (this.GetType() != p.GetType()) - { - return false; - } - - // Return true if the fields match. - // Note that the base class is not invoked because it is - // System.Object, which defines Equals as reference equality. - return (X == p.X) && (Y == p.Y); - } - - public override int GetHashCode() - { - return X * 0x00010000 + Y; - } - - public static bool operator ==(TwoDPoint lhs, TwoDPoint rhs) - { - // Check for null on left side. - if (Object.ReferenceEquals(lhs, null)) - { - if (Object.ReferenceEquals(rhs, null)) - { - // null == null = true. - return true; - } - - // Only the left side is null. - return false; - } - // Equals handles case of null on right side. - return lhs.Equals(rhs); - } - - public static bool operator !=(TwoDPoint lhs, TwoDPoint rhs) - { - return !(lhs == rhs); - } - } - - // For the sake of simplicity, assume a ThreeDPoint IS a TwoDPoint. - class ThreeDPoint : TwoDPoint, IEquatable - { - public int Z { get; private set; } - - public ThreeDPoint(int x, int y, int z) - : base(x, y) - { - if ((z < 1) || (z > 2000)) - { - throw new System.ArgumentException("Point must be in range 1 - 2000"); - } - this.Z = z; - } - - public override bool Equals(object obj) - { - return this.Equals(obj as ThreeDPoint); - } - - public bool Equals(ThreeDPoint p) - { - // If parameter is null, return false. - if (Object.ReferenceEquals(p, null)) - { - return false; - } - - // Optimization for a common success case. - if (Object.ReferenceEquals(this, p)) - { - return true; - } - - // Check properties that this class declares. - if (Z == p.Z) - { - // Let base class check its own fields - // and do the run-time type comparison. - return base.Equals((TwoDPoint)p); - } - else - { - return false; - } - } - - public override int GetHashCode() - { - return (X * 0x100000) + (Y * 0x1000) + Z; - } - - public static bool operator ==(ThreeDPoint lhs, ThreeDPoint rhs) - { - // Check for null. - if (Object.ReferenceEquals(lhs, null)) - { - if (Object.ReferenceEquals(rhs, null)) - { - // null == null = true. - return true; - } - - // Only the left side is null. - return false; - } - // Equals handles the case of null on right side. - return lhs.Equals(rhs); - } - - public static bool operator !=(ThreeDPoint lhs, ThreeDPoint rhs) - { - return !(lhs == rhs); - } - } - - class Program - { - public static void Main() - { - ThreeDPoint pointA = new ThreeDPoint(3, 4, 5); - ThreeDPoint pointB = new ThreeDPoint(3, 4, 5); - ThreeDPoint pointC = null; - int i = 5; - - Console.WriteLine($"pointA.Equals(pointB) = {pointA.Equals(pointB)}"); - Console.WriteLine($"pointA == pointB = {pointA == pointB}"); - Console.WriteLine($"null comparison = {pointA.Equals(pointC)}"); - Console.WriteLine($"Compare to some other type = {pointA.Equals(i)}"); - - TwoDPoint pointD = null; - TwoDPoint pointE = null; - - Console.WriteLine($"Two null TwoDPoints are equal: {pointD == pointE}"); - - pointE = new TwoDPoint(3, 4); - Console.WriteLine($"(pointE == pointA) = {pointE == pointA}"); - Console.WriteLine($"(pointA == pointE) = {pointA == pointE}"); - Console.WriteLine($"(pointA != pointE) = {pointA != pointE}"); - - System.Collections.ArrayList list = new System.Collections.ArrayList(); - list.Add(new ThreeDPoint(3, 4, 5)); - Console.WriteLine($"pointE.Equals(list[0]): {pointE.Equals(list[0])}"); - } - } - - /* Output: - pointA.Equals(pointB) = True - pointA == pointB = True - null comparison = False - Compare to some other type = False - Two null TwoDPoints are equal: True - (pointE == pointA) = False - (pointA == pointE) = False - (pointA != pointE) = True - pointE.Equals(list[0]): False - */ - } - // - - // Test the Hash Code -- this is not in docs - namespace ValueEquality - { - using System; - using System.Collections.Generic; - using System.Linq; - class Hash - { - public static void Main() - { - Random rand = new Random(); - List list = new List(); - for (int x = 0; x < 100000; x++) - { - list.Add(new ThreeDPoint(rand.Next(1, 2000), rand.Next(1, 2000), rand.Next(1, 2000))); - } - - list = (from item in list - select item) - .Distinct() - .ToList(); - - int uniqueObjects = list.Count(); - - Console.WriteLine($"there are {uniqueObjects} unique objects"); - - var uniqueHashCodes = (from item in list - select item.GetHashCode()) - .Distinct(); - - var hashCodeCount = uniqueHashCodes.Count(); - - // This only shows the number of unique values, not the evenness - // of their distribution. For that there is a LINQ query example in the docs - // how to group by a range. - Console.WriteLine($"there are {hashCodeCount} unique hash codes"); - - Console.WriteLine("Distribution:"); - - GroupByRange(uniqueHashCodes); - } - - static int GetRange(int hash, int granularity) - { - if (hash <= 0) - throw new System.ArgumentException("hash must be greater than 0", nameof(hash)); - return hash / (System.Int32.MaxValue / granularity); - } - - private static void GroupByRange(IEnumerable list) - { - Console.WriteLine("\r\nGroup by numeric range and project into a new anonymous type:"); - - var queryNumericRange = - from item in list - group item by GetRange(item, 100) into percentGroup - orderby percentGroup.Key - select percentGroup; - - // Nested foreach required to iterate over groups and group items. - foreach (var hashGroup in queryNumericRange) - { - Console.WriteLine($"Key: {(hashGroup.Key)} Count: {hashGroup.Count()}"); - } - } - } - } - - // This is no longer in docs, replaced by ~docs\docs\csharp\programming-guide\statements-expressions-operators\snippets\how-to-define-value-equality-for-a-type\ValueEqualityStruct\Program.cs - namespace ValueEqualityValueTypes - { - // - using System; - struct TwoDPoint : IEquatable - { - // Read/write automatically implemented properties. - public int X { get; private set; } - public int Y { get; private set; } - - public TwoDPoint(int x, int y) - : this() - { - X = x; - Y = x; - } - - public override bool Equals(object obj) - { - if (obj is TwoDPoint) - { - return this.Equals((TwoDPoint)obj); - } - return false; - } - - public bool Equals(TwoDPoint p) - { - return (X == p.X) && (Y == p.Y); - } - - public override int GetHashCode() - { - return X ^ Y; - } - - public static bool operator ==(TwoDPoint lhs, TwoDPoint rhs) - { - return lhs.Equals(rhs); - } - - public static bool operator !=(TwoDPoint lhs, TwoDPoint rhs) - { - return !(lhs.Equals(rhs)); - } - } - - class Program - { - public static void Main() - { - TwoDPoint pointA = new TwoDPoint(3, 4); - TwoDPoint pointB = new TwoDPoint(3, 4); - int i = 5; - - // Compare using virtual Equals, static Equals, and == and != operators. - // True: - Console.WriteLine($"pointA.Equals(pointB) = {pointA.Equals(pointB)}"); - // True: - Console.WriteLine($"pointA == pointB = {pointA == pointB}"); - // True: - Console.WriteLine($"object.Equals(pointA, pointB) = {object.Equals(pointA, pointB)}"); - // False: - Console.WriteLine($"pointA.Equals(null) = {pointA.Equals(null)}"); - // False: - Console.WriteLine($"(pointA == null) = {pointA == null}"); - // True: - Console.WriteLine($"(pointA != null) = {pointA != null}"); - // False: - Console.WriteLine($"pointA.Equals(i) = {pointA.Equals(i)}"); - // CS0019: - // Console.WriteLine($"pointA == i = {pointA == i}"); - - // Compare unboxed to boxed. - System.Collections.ArrayList list = new System.Collections.ArrayList(); - list.Add(new TwoDPoint(3, 4)); - // True: - Console.WriteLine($"pointA.Equals(list[0]): {pointA.Equals(list[0])}"); - - // Compare nullable to nullable and to non-nullable. - TwoDPoint? pointC = null; - TwoDPoint? pointD = null; - // False: - Console.WriteLine($"pointA == (pointC = null) = {pointA == pointC}"); - // True: - Console.WriteLine($"pointC == pointD = {pointC == pointD}"); - - TwoDPoint temp = new TwoDPoint(3, 4); - pointC = temp; - // True: - Console.WriteLine($"pointA == (pointC = 3,4) = {pointA == pointC}"); - - pointD = temp; - // True: - Console.WriteLine($"pointD == (pointC = 3,4) = {pointD == pointC}"); - } - } - - /* Output: - pointA.Equals(pointB) = True - pointA == pointB = True - Object.Equals(pointA, pointB) = True - pointA.Equals(null) = False - (pointA == null) = False - (pointA != null) = True - pointA.Equals(i) = False - pointE.Equals(list[0]): True - pointA == (pointC = null) = False - pointC == pointD = True - pointA == (pointC = 3,4) = True - pointD == (pointC = 3,4) = True - */ - } - // - - namespace WrapGuidelines2 - { - class Program - { - static void Test5() - { - /* Commented out to remove deliberate compile warning - // - // An over-simplified example of unreachable code. - const int val = 5; - if (val < 4) - { - System.Console.WriteLine("I'll never write anything."); //CS0162 - } - // - */ - } - - void TestMethod(string s) - { - // - // Variable declaration statements. - double area; - double radius = 2; - - // Constant declaration statement. - const double pi = 3.14159; - // - - // - // Expression statement (assignment). - area = 3.14 * (radius * radius); - - // Expression statement (result discarded). - int x = 0; - x++; - - // Expression statement (method invocation). - System.Console.WriteLine(); - - // Expression statement (new object creation). - System.Collections.Generic.List strings = - new System.Collections.Generic.List(); - // - - System.Console.WriteLine(pi.ToString()); - } - - bool GetNextMessage() { return true; } - - bool ProcessMessage() - { - if (GetNextMessage()) - { - // Code to process message... - return true; - } - else - { - return false; - } - } - bool done = false; - // - void ProcessMessages() - { - while (ProcessMessage()) - ; // Statement needed here. - } - - void F() - { - //... - if (done) goto exit; - //... - exit: - ; // Statement needed here. - } - // - - void G() - { - bool b = true; - // - // Recommended style. Embedded statement in block. - foreach (string s in System.IO.Directory.GetDirectories( - System.Environment.CurrentDirectory)) - { - System.Console.WriteLine(s); - } - - // Not recommended. - foreach (string s in System.IO.Directory.GetDirectories( - System.Environment.CurrentDirectory)) - System.Console.WriteLine(s); - // - - /* - // - if(pointB == true) - //Error CS1023: - int radius = 5; - // - */ - - // - if (b == true) - { - // OK: - System.DateTime d = System.DateTime.Now; - System.Console.WriteLine(d.ToLongDateString()); - } - // - } - string S() - { - // - foreach (string s in System.IO.Directory.GetDirectories( - System.Environment.CurrentDirectory)) - { - if (s.StartsWith("CSharp")) - { - if (s.EndsWith("TempFolder")) - { - return s; - } - } - } - return "Not found."; - // - } - } - } -} diff --git a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/Program.cs b/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/Program.cs deleted file mode 100644 index 3ae6c746e7ace..0000000000000 --- a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/Program.cs +++ /dev/null @@ -1,2 +0,0 @@ -// See https://aka.ms/new-console-template for more information -ExpressionBodiedMembers.Example.Main(); diff --git a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-ctor.cs b/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-ctor.cs deleted file mode 100644 index e43962db2811e..0000000000000 --- a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-ctor.cs +++ /dev/null @@ -1,46 +0,0 @@ -using System; - -namespace ExprBodied; - -// -public class Location -{ - private string locationName; - - public Location(string name) => Name = name; - - public string Name - { - get => locationName; - set => locationName = value; - } -} - -// Example with multiple parameters -public class Point -{ - public double X { get; } - public double Y { get; } - - // Constructor with multiple parameters - public Point(double x, double y) => (X, Y) = (x, y); - - // Constructor with single parameter (creates point at origin on axis) - public Point(double coordinate) => (X, Y) = (coordinate, 0); -} -// - -public class Example -{ - public static void Main() - { - var city = new Location("New York City"); - Console.WriteLine(city.Name); - - // Examples with multiple constructor parameters - var point1 = new Point(3.0, 4.0); - var point2 = new Point(5.0); - Console.WriteLine($"Point 1: ({point1.X}, {point1.Y})"); - Console.WriteLine($"Point 2: ({point2.X}, {point2.Y})"); - } -} \ No newline at end of file diff --git a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-event.cs b/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-event.cs deleted file mode 100644 index 8ca1ddf83c448..0000000000000 --- a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-event.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; - -namespace ExprBodied; - -// -public class ChangedEventArgs : EventArgs -{ - public required int NewValue { get; init; } -} - -public class ObservableNum(int _value) -{ - public event EventHandler ChangedGeneric = default!; - - public event EventHandler Changed - { - // Note that, while this is syntactically valid, it won't work as expected because it's creating a new delegate object with each call. - add => ChangedGeneric += (sender, args) => value(sender, args); - remove => ChangedGeneric -= (sender, args) => value(sender, args); - } - - public int Value - { - get => _value; - set => ChangedGeneric?.Invoke(this, new() { NewValue = (_value = value) }); - } -} -// - -public class ExpressionExample -{ - public static void Main() - { - void PrintingHandler(object? sender, object? args) - => Console.WriteLine((args as ChangedEventArgs)?.NewValue); - ObservableNum num = new(2); - num.Changed += PrintingHandler; - num.Value = 3; - num.Changed -= PrintingHandler; - num.Value = 1; // Still prints! - } -} diff --git a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-indexers.cs b/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-indexers.cs deleted file mode 100644 index f207b760870a2..0000000000000 --- a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-indexers.cs +++ /dev/null @@ -1,30 +0,0 @@ -// -using System; -using System.Collections.Generic; - -namespace SportsExample; - -public class Sports -{ - private string[] types = [ "Baseball", "Basketball", "Football", - "Hockey", "Soccer", "Tennis", - "Volleyball" ]; - - public string this[int i] - { - get => types[i]; - set => types[i] = value; - } -} -// - - class Program - { - static void Main() - { - var s = new Sports(); - Console.WriteLine(s[2]); - s[1] = "Softball"; - Console.WriteLine(s[1]); - } -} diff --git a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-methods.cs b/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-methods.cs deleted file mode 100644 index a11b3f27a94f9..0000000000000 --- a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-methods.cs +++ /dev/null @@ -1,40 +0,0 @@ -using System; - -namespace ExpressionBodiedMembers; - -public class Person -{ - public Person(string firstName, string lastName) - { - fname = firstName; - lname = lastName; - } - - private string fname; - private string lname; - - public override string ToString() => $"{fname} {lname}".Trim(); - public void DisplayName() => Console.WriteLine(ToString()); - - // Expression-bodied methods with parameters - public string GetFullName(string title) => $"{title} {fname} {lname}"; - public int CalculateAge(int birthYear) => DateTime.Now.Year - birthYear; - public bool IsOlderThan(int age) => CalculateAge(1990) > age; - public string FormatName(string format) => format.Replace("{first}", fname).Replace("{last}", lname); -} - -class Example -{ - public static void Main() - { - Person p = new Person("Mandy", "Dejesus"); - Console.WriteLine(p); - p.DisplayName(); - - // Examples with parameters - Console.WriteLine(p.GetFullName("Dr.")); - Console.WriteLine($"Age: {p.CalculateAge(1990)}"); - Console.WriteLine($"Is older than 25: {p.IsOlderThan(25)}"); - Console.WriteLine(p.FormatName("Last: {last}, First: {first}")); - } -} diff --git a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-readonly.cs b/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-readonly.cs deleted file mode 100644 index ed49e29385697..0000000000000 --- a/samples/snippets/csharp/programming-guide/classes-and-structs/ExpressionBodiedMembers/expr-bodied-readonly.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; - -namespace ExprBodiedReadonlyProperties; - -// -public class Location -{ - private string locationName; - - public Location(string name) - { - locationName = name; - } - - public string Name => locationName; -} -// - -public class Example -{ - public static void Main() - { - var city = new Location("New York City"); - Console.WriteLine(city.Name); - } -}