From 55879ab28f617debcb7cacb41e38ef6ee7de94e4 Mon Sep 17 00:00:00 2001 From: "Tom Pratt (Aquent LLC)" Date: Fri, 24 Mar 2017 12:13:56 -0700 Subject: [PATCH 1/2] Update language identifiers and styleguide. --- docs/core/deploying/index.md | 4 +- .../testing/unit-testing-with-dotnet-test.md | 8 +-- docs/core/testing/unit-testing-with-mstest.md | 8 +-- .../using-on-mac-vs-full-solution.md | 4 +- docs/csharp/delegate-class.md | 14 ++--- docs/csharp/delegates-patterns.md | 24 ++++----- docs/csharp/delegates-strongly-typed.md | 8 +-- docs/csharp/event-pattern.md | 26 ++++----- docs/csharp/events-overview.md | 8 +-- docs/csharp/expression-classes.md | 4 +- docs/csharp/expression-trees-building.md | 24 ++++----- docs/csharp/expression-trees-execution.md | 8 +-- docs/csharp/expression-trees-explained.md | 4 +- docs/csharp/expression-trees-interpreting.md | 22 ++++---- docs/csharp/expression-trees-translating.md | 10 ++-- .../debugging-with-visual-studio-2017.md | 4 +- .../testing-library-with-visual-studio.md | 2 +- .../getting-started/with-visual-studio.md | 2 +- docs/csharp/indexers.md | 14 ++--- docs/csharp/iterators.md | 28 +++++----- docs/csharp/lambda-expressions.md | 4 +- .../compiler-messages/cs0015.md | 2 +- .../compiler-messages/cs0052.md | 2 +- .../compiler-messages/cs0103.md | 4 +- .../compiler-messages/cs0163.md | 2 +- .../compiler-messages/cs0165.md | 4 +- .../compiler-messages/cs0173.md | 4 +- .../compiler-messages/cs0246.md | 6 +-- .../compiler-messages/cs0260.md | 2 +- .../compiler-messages/cs0266.md | 2 +- .../compiler-messages/cs0269.md | 4 +- .../compiler-messages/cs0304.md | 8 +-- .../compiler-messages/cs0417.md | 2 +- .../compiler-messages/cs0445.md | 2 +- .../compiler-messages/cs0467.md | 2 +- .../compiler-messages/cs0579.md | 2 +- .../compiler-messages/cs1009.md | 6 +-- .../compiler-messages/cs1019.md | 4 +- .../compiler-messages/cs1061.md | 2 +- .../compiler-messages/cs1501.md | 2 +- .../compiler-messages/cs1519.md | 2 +- .../compiler-messages/cs1540.md | 2 +- .../compiler-messages/cs1612.md | 6 +-- .../compiler-messages/cs1705.md | 8 +-- .../compiler-messages/cs1708.md | 2 +- .../compiler-messages/cs1729.md | 2 +- .../compiler-messages/cs1956.md | 2 +- .../compiler-messages/cs2032.md | 2 +- .../compiler-messages/cs4014.md | 6 +-- .../compiler-options/link-compiler-option.md | 2 +- .../preferreduilang-compiler-option.md | 2 +- .../language-reference/keywords/async.md | 4 +- .../language-reference/keywords/await.md | 6 +-- .../language-reference/keywords/decimal.md | 2 +- .../language-reference/keywords/dynamic.md | 2 +- .../keywords/fixed-statement.md | 2 +- .../language-reference/keywords/float.md | 2 +- .../csharp/language-reference/keywords/for.md | 2 +- .../keywords/group-clause.md | 2 +- .../language-reference/keywords/if-else.md | 4 +- .../csharp/language-reference/keywords/int.md | 6 +-- .../keywords/interpolated-strings.md | 4 +- docs/csharp/language-reference/keywords/is.md | 8 +-- .../language-reference/keywords/long.md | 12 ++--- .../language-reference/keywords/nameof.md | 14 ++--- .../keywords/out-parameter-modifier.md | 2 +- .../language-reference/keywords/sbyte.md | 14 ++--- .../language-reference/keywords/short.md | 14 ++--- .../language-reference/keywords/sizeof.md | 2 +- .../language-reference/keywords/static.md | 2 +- .../language-reference/keywords/string.md | 16 +++--- .../language-reference/keywords/switch.md | 10 ++-- .../language-reference/keywords/throw.md | 2 +- .../language-reference/keywords/try-catch.md | 14 ++--- .../language-reference/keywords/uint.md | 6 +-- .../language-reference/keywords/ulong.md | 8 +-- .../language-reference/keywords/ushort.md | 14 ++--- .../keywords/using-directive.md | 8 +-- .../keywords/using-static.md | 2 +- .../language-reference/keywords/when.md | 4 +- .../keywords/where-generic-type-constraint.md | 6 +-- .../language-reference/keywords/yield.md | 4 +- .../operators/lambda-operator.md | 6 +-- .../operators/null-conditional-operators.md | 4 +- .../preprocessor-define.md | 2 +- .../language-reference/tokens/verbatim.md | 2 +- ...ly-specify-predicate-filters-at-runtime.md | 2 +- .../linq/join-by-using-composite-keys.md | 4 +- docs/csharp/linq/write-linq-queries.md | 6 +-- docs/csharp/methods.md | 10 ++-- docs/csharp/misc/cs0168.md | 2 +- docs/csharp/misc/cs0415.md | 2 +- docs/csharp/misc/cs0428.md | 2 +- docs/csharp/misc/cs0542.md | 6 +-- docs/csharp/misc/cs0625.md | 2 +- docs/csharp/misc/cs0626.md | 2 +- docs/csharp/misc/cs0662.md | 2 +- docs/csharp/misc/cs0664.md | 2 +- docs/csharp/misc/cs0668.md | 2 +- docs/csharp/misc/cs0669.md | 2 +- docs/csharp/misc/cs1944.md | 2 +- docs/csharp/modern-events.md | 4 +- .../classes-and-structs/anonymous-types.md | 4 +- .../auto-implemented-properties.md | 2 +- ...-access-a-collection-class-with-foreach.md | 4 +- ...-class-with-auto-implemented-properties.md | 2 +- .../how-to-override-the-tostring-method.md | 2 +- ...g-when-to-use-override-and-new-keywords.md | 36 ++++++------- .../classes-and-structs/methods.md | 4 +- ...static-classes-and-static-class-members.md | 2 +- .../assemblies-gac/friend-assemblies.md | 2 +- ...d-use-assemblies-using-the-command-line.md | 14 ++--- .../how-to-create-signed-friend-assemblies.md | 8 +-- ...ow-to-create-unsigned-friend-assemblies.md | 8 +-- ...mation-from-microsoft-office-assemblies.md | 2 +- ...rom-managed-assemblies-in-visual-studio.md | 12 ++--- .../concepts/async/async-return-types.md | 20 +++---- ...cancel-an-async-task-or-a-list-of-tasks.md | 24 ++++----- ...ncel-async-tasks-after-a-period-of-time.md | 4 +- ...ining-async-tasks-after-one-is-complete.md | 14 ++--- .../async/control-flow-in-async-programs.md | 16 +++--- .../handling-reentrancy-in-async-apps.md | 26 ++++----- ...async-walkthrough-by-using-task-whenall.md | 24 ++++----- ...ts-in-parallel-by-using-async-and-await.md | 12 ++--- .../programming-guide/concepts/async/index.md | 8 +-- ...tasks-and-process-them-as-they-complete.md | 12 ++--- .../async/using-async-for-file-access.md | 10 ++-- ...essing-the-web-by-using-async-and-await.md | 42 +++++++-------- ...ccessing-attributes-by-using-reflection.md | 6 +-- .../concepts/attributes/attributeusage.md | 20 +++---- .../concepts/attributes/common-attributes.md | 18 +++---- .../attributes/creating-custom-attributes.md | 8 +-- ...reate-a-c-cpp-union-by-using-attributes.md | 4 +- .../concepts/attributes/index.md | 20 +++---- .../concepts/caller-information.md | 2 +- .../programming-guide/concepts/collections.md | 28 +++++----- .../creating-variant-generic-interfaces.md | 22 ++++---- .../covariance-contravariance/index.md | 8 +-- ...e-for-func-and-action-generic-delegates.md | 4 +- .../using-variance-in-delegates.md | 4 +- ...e-in-interfaces-for-generic-collections.md | 4 +- .../variance-in-delegates.md | 22 ++++---- .../variance-in-generic-interfaces.md | 8 +-- .../how-to-execute-expression-trees.md | 2 +- .../how-to-modify-expression-trees.md | 4 +- ...pression-trees-to-build-dynamic-queries.md | 2 +- .../concepts/expression-trees/index.md | 10 ++-- .../programming-guide/concepts/iterators.md | 10 ++-- ...nts-attributes-and-nodes-to-an-xml-tree.md | 2 +- ...name-and-xnamespace-objects-linq-to-xml.md | 4 +- .../concepts/linq/chaining-queries-example.md | 2 +- ...ining-standard-query-operators-together.md | 2 +- .../concepts/linq/cloning-vs-attaching.md | 2 +- .../comparison-of-xpath-and-linq-to-xml.md | 4 +- .../concepts/linq/converting-data-types.md | 2 +- .../linq/creating-xml-trees-linq-to-xml-2.md | 16 +++--- .../linq/deferred-execution-example.md | 2 +- ...-outputs-office-open-xml-document-parts.md | 2 +- .../concepts/linq/filtering-data.md | 2 +- .../linq/finding-text-in-word-documents.md | 4 +- .../finding-the-default-paragraph-style.md | 2 +- .../functional-construction-linq-to-xml.md | 4 +- .../concepts/linq/grouping-data.md | 2 +- ...-to-add-custom-methods-for-linq-queries.md | 22 ++++---- .../linq/how-to-build-linq-to-xml-examples.md | 2 +- .../how-to-calculate-intermediate-values.md | 4 +- .../linq/how-to-catch-parsing-errors.md | 2 +- ...-to-chain-axis-method-calls-linq-to-xml.md | 6 +-- ...ge-the-namespace-for-an-entire-xml-tree.md | 2 +- ...ine-and-compare-string-collections-linq.md | 2 +- ...e-linq-queries-with-regular-expressions.md | 2 +- ...ompare-the-contents-of-two-folders-linq.md | 2 +- ...e-column-values-in-a-csv-text-file-linq.md | 2 +- ...-control-namespace-prefixes-linq-to-xml.md | 2 +- ...how-to-control-the-type-of-a-projection.md | 2 +- ...-occurrences-of-a-word-in-a-string-linq.md | 2 +- ...-a-document-with-namespaces-linq-to-xml.md | 10 ++-- .../how-to-create-a-tree-from-an-xmlreader.md | 2 +- .../how-to-create-hierarchy-using-grouping.md | 2 +- .../how-to-debug-empty-query-results-sets.md | 4 +- ...ilter-on-an-attribute-xpath-linq-to-xml.md | 2 +- .../how-to-filter-on-an-optional-element.md | 4 +- ...-to-filter-on-element-names-linq-to-xml.md | 4 +- ...-find-a-child-element-xpath-linq-to-xml.md | 2 +- ...ist-of-child-elements-xpath-linq-to-xml.md | 2 +- ...descendant-using-the-descendants-method.md | 4 +- ...of-two-location-paths-xpath-linq-to-xml.md | 2 +- .../how-to-find-all-nodes-in-a-namespace.md | 4 +- ...tribute-of-the-parent-xpath-linq-to-xml.md | 2 +- ...nd-an-element-with-a-specific-attribute.md | 4 +- ...n-element-with-a-specific-child-element.md | 4 +- ...-with-a-specific-name-xpath-linq-to-xml.md | 2 +- ...nts-based-on-position-xpath-linq-to-xml.md | 2 +- ...d-descendant-elements-xpath-linq-to-xml.md | 2 +- ...ts-of-a-child-element-xpath-linq-to-xml.md | 2 +- ...escendants-with-a-specific-element-name.md | 4 +- ...ements-in-a-namespace-xpath-linq-to-xml.md | 2 +- ...-a-specific-attribute-xpath-linq-to-xml.md | 2 +- ...nd-preceding-siblings-xpath-linq-to-xml.md | 2 +- ...find-related-elements-xpath-linq-to-xml.md | 2 +- ...to-find-sibling-nodes-xpath-linq-to-xml.md | 2 +- ...ate-preceding-sibling-xpath-linq-to-xml.md | 2 +- ...find-the-root-element-xpath-linq-to-xml.md | 2 +- ...e-set-difference-between-two-lists-linq.md | 2 +- .../how-to-generate-text-files-from-xml.md | 2 +- .../how-to-generate-xml-from-csv-files.md | 2 +- .../how-to-group-files-by-extension-linq.md | 2 +- ...join-content-from-dissimilar-files-linq.md | 2 +- ...how-to-join-two-collections-linq-to-xml.md | 2 +- .../linq/how-to-list-all-nodes-in-a-tree.md | 2 +- .../linq/how-to-load-xml-from-a-file.md | 2 +- ...w-to-modify-an-office-open-xml-document.md | 2 +- .../concepts/linq/how-to-parse-a-string.md | 2 +- ...eaming-transform-of-large-xml-documents.md | 4 +- ...treaming-transformations-of-text-to-xml.md | 2 +- ...pulate-an-xml-tree-from-the-file-system.md | 2 +- ...-xml-tree-with-an-xmlwriter-linq-to-xml.md | 2 +- ...-collections-from-multiple-sources-linq.md | 4 +- .../how-to-project-a-new-type-linq-to-xml.md | 2 +- .../linq/how-to-project-an-anonymous-type.md | 2 +- .../linq/how-to-project-an-object-graph.md | 2 +- .../how-to-query-an-arraylist-with-linq.md | 2 +- ...ssembly-s-metadata-with-reflection-linq.md | 2 +- ...o-query-for-characters-in-a-string-linq.md | 2 +- ...uplicate-files-in-a-directory-tree-linq.md | 2 +- ...iles-with-a-specified-attribute-or-name.md | 2 +- ...t-contain-a-specified-set-of-words-linq.md | 2 +- ...-file-or-files-in-a-directory-tree-linq.md | 2 +- ...umber-of-bytes-in-a-set-of-folders-linq.md | 2 +- .../how-to-query-linq-to-xml-using-xpath.md | 2 +- ...y-the-contents-of-files-in-a-folder-lin.md | 2 +- ...w-to-read-and-write-an-encoded-document.md | 2 +- ...der-the-fields-of-a-delimited-file-linq.md | 2 +- ...-a-collection-of-attributes-linq-to-xml.md | 2 +- ...ve-a-collection-of-elements-linq-to-xml.md | 2 +- ...retrieve-a-single-attribute-linq-to-xml.md | 6 +-- ...ieve-a-single-child-element-linq-to-xml.md | 4 +- ...graphs-from-an-office-open-xml-document.md | 2 +- ...etrieve-the-shallow-value-of-an-element.md | 2 +- ...e-the-value-of-an-attribute-linq-to-xml.md | 4 +- ...eve-the-value-of-an-element-linq-to-xml.md | 8 +-- ...-serialize-using-datacontractserializer.md | 2 +- .../how-to-serialize-using-xmlserializer.md | 2 +- .../how-to-sort-elements-on-multiple-keys.md | 4 +- .../concepts/linq/how-to-sort-elements.md | 4 +- ...ter-text-data-by-any-word-or-field-linq.md | 2 +- ...le-into-many-files-by-using-groups-linq.md | 2 +- ...-stream-xml-fragments-from-an-xmlreader.md | 2 +- ...ments-with-access-to-header-information.md | 2 +- ...w-to-transform-the-shape-of-an-xml-tree.md | 4 +- ...form-linq-to-xml-trees-in-an-xslt-style.md | 8 +-- .../how-to-validate-using-xsd-linq-to-xml.md | 4 +- ...ork-with-dictionaries-using-linq-to-xml.md | 4 +- .../how-to-write-a-linq-to-xml-axis-method.md | 2 +- ...ry-that-finds-elements-based-on-context.md | 4 +- ...w-to-write-queries-on-xml-in-namespaces.md | 4 +- ...to-write-queries-with-complex-filtering.md | 4 +- ...-vs-functional-construction-linq-to-xml.md | 4 +- .../linq/intermediate-materialization.md | 2 +- .../linq/introduction-to-linq-queries.md | 2 +- .../concepts/linq/linq-to-xml-events.md | 2 +- .../concepts/linq/linq-to-xml-overview.md | 6 +-- .../concepts/linq/linq-to-xml-vs-dom.md | 6 +-- .../linq/maintaining-name-value-pairs.md | 4 +- ...e-code-imperative-code-bugs-linq-to-xml.md | 14 ++--- ...formance-of-chained-queries-linq-to-xml.md | 2 +- ...tomization-of-xname-objects-linq-to-xml.md | 8 +-- .../concepts/linq/programming-with-nodes.md | 14 ++--- .../projecting-xml-in-a-different-shape.md | 2 +- .../concepts/linq/projection-operations.md | 6 +-- ...ng-an-xdocument-vs-querying-an-xelement.md | 6 +-- .../linq/refactoring-into-pure-functions.md | 6 +-- .../linq/refactoring-using-a-pure-function.md | 2 +- .../refactoring-using-an-extension-method.md | 6 +-- ...s-attributes-and-nodes-from-an-xml-tree.md | 2 +- ...rieving-the-paragraphs-and-their-styles.md | 6 +-- .../retrieving-the-text-of-the-paragraphs.md | 2 +- .../linq/scope-of-default-namespaces.md | 4 +- ...rializing-to-an-xmlreader-invoking-xslt.md | 2 +- .../serializing-with-an-xml-declaration.md | 4 +- .../shape-of-wordprocessingml-documents.md | 2 +- .../concepts/linq/sorting-data.md | 8 +-- .../linq/standard-query-operators-overview.md | 2 +- ...statically-compiled-queries-linq-to-xml.md | 8 +-- .../using-xslt-to-transform-an-xml-tree.md | 2 +- .../linq/xattribute-class-overview.md | 4 +- .../concepts/linq/xdocument-class-overview.md | 2 +- .../concepts/linq/xelement-class-overview.md | 4 +- .../concepts/object-oriented-programming.md | 50 ++++++++--------- .../programming-guide/concepts/reflection.md | 4 +- ...ow-to-read-object-data-from-an-xml-file.md | 2 +- ...how-to-write-object-data-to-an-xml-file.md | 2 +- ...h-persisting-an-object-in-visual-studio.md | 18 +++---- .../threading/how-to-use-a-thread-pool.md | 2 +- .../threading/multithreaded-applications.md | 6 +-- ...urn-values-for-multithreaded-procedures.md | 8 +-- .../concepts/threading/thread-pooling.md | 2 +- .../threading/thread-synchronization.md | 8 +-- .../concepts/threading/thread-timers.md | 2 +- ...ing-with-the-backgroundworker-component.md | 10 ++-- .../programming-guide/enumeration-types.md | 2 +- ...hat-conform-to-net-framework-guidelines.md | 12 ++--- .../how-to-create-a-file-or-folder.md | 4 +- ...ormation-about-files-folders-and-drives.md | 2 +- ...how-to-iterate-through-a-directory-tree.md | 2 +- .../nullable-types/boxing-nullable-types.md | 10 ++-- .../how-to-safely-cast-from-bool-to-bool.md | 2 +- .../equality-comparisons.md | 2 +- .../lambda-expressions.md | 30 +++++------ .../operators.md | 2 +- .../overloadable-operators.md | 4 +- .../how-to-convert-a-string-to-a-datetime.md | 2 +- ...how-to-parse-strings-using-string-split.md | 2 +- .../types/casting-and-type-conversions.md | 4 +- docs/csharp/programming-guide/types/index.md | 10 ++-- docs/csharp/properties.md | 22 ++++---- docs/csharp/tutorials/console-teleprompter.md | 38 ++++++------- docs/csharp/tutorials/console-webapiclient.md | 54 +++++++++---------- docs/csharp/tutorials/inheritance.md | 8 +-- docs/csharp/tutorials/microservices.md | 4 +- docs/csharp/tutorials/string-interpolation.md | 4 +- docs/csharp/tutorials/working-with-linq.md | 38 ++++++------- .../async.md | 10 ++-- docs/standard/delegates-lambdas.md | 10 ++-- .../garbagecollection/implementing-dispose.md | 16 +++--- .../garbagecollection/using-objects.md | 8 +-- docs/standard/generics.md | 2 +- docs/standard/native-interop.md | 18 +++---- docs/standard/using-linq.md | 28 +++++----- ...ith-the-lineshape-control-visual-studio.md | 2 +- ...e-ovalshape-and-rectangleshape-controls.md | 2 +- ...le-tabbing-between-shapes-visual-studio.md | 2 +- ...-the-datarepeater-control-visual-studio.md | 2 +- samples/README.md | 2 +- styleguide/template.md | 30 ++++++++++- 335 files changed, 1058 insertions(+), 1032 deletions(-) diff --git a/docs/core/deploying/index.md b/docs/core/deploying/index.md index a77890dcb1e10..5b51a3d67cc74 100644 --- a/docs/core/deploying/index.md +++ b/docs/core/deploying/index.md @@ -47,7 +47,7 @@ Deploying a framework-dependent deployment with no third-party dependencies simp 2. Open the `Program.cs` file in an editor, and replace the auto-generated code with the following code. It prompts the user to enter text, and then displays the individual words entered by the user. It uses the regular expression `\w+` to separate the words in the input text. - ```cs + ```csharp using System; using System.Text.RegularExpressions; @@ -142,7 +142,7 @@ Deploying a self-contained deployment with no third-party dependencies involves 2. Open the `Program.cs` file in an editor, and replace the auto-generated code with the following code. It prompts the user to enter text, and then displays the individual words entered by the user. It uses the regular expression `\w+` to separate the words in the input text. - ```cs + ```csharp using System; using System.Text.RegularExpressions; diff --git a/docs/core/testing/unit-testing-with-dotnet-test.md b/docs/core/testing/unit-testing-with-dotnet-test.md index 27984d557df4b..0e79f2b629425 100644 --- a/docs/core/testing/unit-testing-with-dotnet-test.md +++ b/docs/core/testing/unit-testing-with-dotnet-test.md @@ -26,7 +26,7 @@ Open a shell window. Create a directory called *unit-testing-using-dotnet-test* Make *PrimeService* the current directory and run [`dotnet new classlib`](../tools/dotnet-new.md) to create the source project. Rename *Class1.cs* to *PrimeService.cs*. To use test-driven development (TDD), you'll create a failing implementation of the `PrimeService` class: -```cs +```csharp using System; namespace Prime.Services @@ -97,7 +97,7 @@ Before building the library or the tests, execute [`dotnet restore`](../tools/do The TDD approach calls for writing one failing test, making it pass, then repeating the process. Remove *UnitTest1.cs* from the *PrimeService.Tests* directory and create a new C# file named *PrimeService_IsPrimeShould.cs* with the following content: -```cs +```csharp using Xunit; using Prime.Services; @@ -128,7 +128,7 @@ The `[Fact]` attribute denotes a method as a single test. Execute [`dotnet test` Your test fails. You haven't created the implementation yet. Write the simplest code in the `PrimeService` class to make this test pass: -```cs +```csharp public bool IsPrime(int candidate) { if (candidate == 1) @@ -151,7 +151,7 @@ Instead of creating new tests, leverage these two attributes to create a single Run `dotnet test`, and two of these tests fail. To make all of the tests pass, change the `if` clause at the beginning of the method: -```cs +```csharp if (candidate < 2) ``` diff --git a/docs/core/testing/unit-testing-with-mstest.md b/docs/core/testing/unit-testing-with-mstest.md index 288e6a9a8d199..16bfb2d9cb1b5 100644 --- a/docs/core/testing/unit-testing-with-mstest.md +++ b/docs/core/testing/unit-testing-with-mstest.md @@ -26,7 +26,7 @@ Open a shell window. Create a directory called *unit-testing-using-dotnet-test* Make *PrimeService* the current directory and run [`dotnet new classlib`](../tools/dotnet-new.md) to create the source project. Rename *Class1.cs* to *PrimeService.cs*. To use test-driven development (TDD), you'll create a failing implementation of the `PrimeService` class: -```cs +```csharp using System; namespace Prime.Services @@ -97,7 +97,7 @@ Before building the library or the tests, execute [`dotnet restore`](../tools/do The TDD approach calls for writing one failing test, making it pass, then repeating the process. Remove *UnitTest1.cs* from the *PrimeService.Tests* directory and create a new C# file named *PrimeService_IsPrimeShould.cs* with the following content: -```cs +```csharp using Microsoft.VisualStudio.TestTools.UnitTesting; using Prime.Services; @@ -130,7 +130,7 @@ Save this file and execute [`dotnet test`](../tools/dotnet-test.md) to build the Your test fails. You haven't created the implementation yet. Write the simplest code in the `PrimeService` class to make this test pass: -```cs +```csharp public bool IsPrime(int candidate) { if (candidate == 1) @@ -153,7 +153,7 @@ Instead of creating new tests, leverage these two attributes to create a single Run `dotnet test`, and two of these tests fail. To make all of the tests pass, change the `if` clause at the beginning of the method: -```cs +```csharp if (candidate < 2) ``` diff --git a/docs/core/tutorials/using-on-mac-vs-full-solution.md b/docs/core/tutorials/using-on-mac-vs-full-solution.md index df443b54b9a17..4e1cbd41cd0cb 100644 --- a/docs/core/tutorials/using-on-mac-vs-full-solution.md +++ b/docs/core/tutorials/using-on-mac-vs-full-solution.md @@ -88,7 +88,7 @@ Unit tests provide automated software testing during your development and publis 1. Open the file and replace the code with the following: - ```cs + ```csharp using Xunit; using TextUtils; using System.Diagnostics; @@ -128,7 +128,7 @@ Unit tests provide automated software testing during your development and publis 1. Testing individual return values with a `Fact` is only the beginning of what you can do with unit testing. Another powerful technique allows you to test several values at once using a `Theory`. Add the following method to your `TextUtils_GetWordCountShould` class. You have two methods in the class after you add this method: - ```cs + ```csharp [Theory] [InlineData(0, "Ting", "Does not appear in the string.")] [InlineData(1, "Ting", "Ting appears once.")] diff --git a/docs/csharp/delegate-class.md b/docs/csharp/delegate-class.md index 15752ee476da9..9eaf89adc560d 100644 --- a/docs/csharp/delegate-class.md +++ b/docs/csharp/delegate-class.md @@ -35,7 +35,7 @@ definition. Let's continue to use the List.Sort() method as our example. The first step is to create a type for the comparison delegate: -```cs +```csharp // From the .NET Core library // Define the delegate type: @@ -69,7 +69,7 @@ After defining the delegate, you can create an instance of that type. Like all variables in C#, you cannot declare delegate instances directly in a namespace, or in the global namespace. -```cs +```csharp // inside a class definition: // Declare an instance of that type: @@ -88,7 +88,7 @@ You invoke the methods that are in the invocation list of a delegate by calling that delegate. Inside the `Sort()` method, the code will call the comparison method to determine which order to place objects: -```cs +```csharp int result = comparator(left, right); ``` @@ -115,7 +115,7 @@ adds the method to the invocation list of that delegate object. Suppose you wanted to sort a list of strings by their length. Your comparison function might be the following: -```cs +```csharp private static int CompareLength(string left, string right) { return left.Length.CompareTo(right.Length); @@ -131,7 +131,7 @@ the delegate object, and can access it through that delegate. You create that relationship by passing that method to the `List.Sort()` method: -```cs +```csharp phrases.Sort(CompareLength); ``` @@ -143,7 +143,7 @@ an invocation target. You could also have been explicit by declaring a variable of type 'Comparison` and doing an assignment: -```cs +```csharp Comparison comparer = CompareLength; phrases.Sort(comparer); ``` @@ -152,7 +152,7 @@ In uses where the method being used as a delegate target is a small method, it's common to use [Lambda Expression](lambda-expressions.md) syntax to perform the assignment: -```cs +```csharp Comparison comparer = (left, right) => left.Length.CompareTo(right.Length); phrases.Sort(comparer); ``` diff --git a/docs/csharp/delegates-patterns.md b/docs/csharp/delegates-patterns.md index a3caf7efd4b9d..340ba2f03697c 100644 --- a/docs/csharp/delegates-patterns.md +++ b/docs/csharp/delegates-patterns.md @@ -23,7 +23,7 @@ One excellent example for this kind of design is LINQ. The LINQ Query Expression Pattern relies on delegates for all of its features. Consider this simple example: -```cs +```csharp var smallNumbers = numbers.Where(n => n < 10); ``` @@ -34,7 +34,7 @@ implementation of the delegate for this specific purpose. The prototype for the Where method is: -```cs +```csharp public static IEnumerable Where (IEnumerable source, Func predicate); ``` @@ -85,7 +85,7 @@ Let's start small: the initial implementation will accept new messages, and write them using any attached delegate. You can start with one delegate that writes messages to the console. -```cs +```csharp public static class Logger { public static Action WriteMessage; @@ -101,7 +101,7 @@ The static class above is the simplest thing that can work. We need to write the single implementation for the method that writes messages to the console: -```cs +```csharp public static void LogToConsole(string message) { Console.Error.WriteLine(message); @@ -111,7 +111,7 @@ public static void LogToConsole(string message) Finally, you need to hook up the delegate by attaching it to the WriteMessage delegate declared in the logger: -```cs +```csharp Logger.WriteMessage += LogToConsole; ``` @@ -137,7 +137,7 @@ creating other logging mechanisms. Next, let's add a few arguments to the `LogMessage()` method so that your log class creates more structured messages: -```cs +```csharp // Logger implementation two public enum Severity { @@ -164,7 +164,7 @@ public static class Logger Next, let's make use of that `Severity` argument to filter the messages that are sent to the log's output. -```cs +```csharp public static class Logger { public static Action WriteMessage; @@ -205,7 +205,7 @@ each message is generated. Here is that file based logger: -```cs +```csharp public class FileLogger { private readonly string logPath; @@ -238,14 +238,14 @@ public class FileLogger Once you've created this class, you can instantiate it and it attaches its LogMessage method to the Logger component: -```cs +```csharp var file = new FileLogger("log.txt"); ``` These two are not mutually exclusive. You could attach both log methods and generate messages to the console and a file: -```cs +```csharp var fileOutput = new FileLogger("log.txt"); Logger.WriteMessage += LogToConsole; ``` @@ -253,7 +253,7 @@ Logger.WriteMessage += LogToConsole; Later, even in the same application, you can remove one of the delegates without any other issues to the system: -```cs +```csharp Logger.WriteMessage -= LogToConsole; ``` @@ -295,7 +295,7 @@ You may prefer a design that silently continues when no methods have been attached. This is easy using the null conditional operator, combined with the `Delegate.Invoke()` method: -```cs +```csharp public static void LogMessage(string msg) { WriteMessage?.Invoke(msg); diff --git a/docs/csharp/delegates-strongly-typed.md b/docs/csharp/delegates-strongly-typed.md index 4968af31b3811..bb66cded2bb8b 100644 --- a/docs/csharp/delegates-strongly-typed.md +++ b/docs/csharp/delegates-strongly-typed.md @@ -36,7 +36,7 @@ when you need new method declarations. The first of these types is the @System.Action type, and several variations: -```cs +```csharp public delegate void Action(); public delegate void Action(T arg); public delegate void Action(T1 arg1, T2 arg2); @@ -56,7 +56,7 @@ Use one of the `Action` types for any delegate type that has a void return type. The framework also includes several generic delegate types that you can use for delegate types that return values: -```cs +```csharp public delegate TResult Func(); public delegate TResult Func(T1 arg); public delegate TResult Func(T1 arg1, T2 arg2); @@ -77,14 +77,14 @@ There's also a specialized @System.Predicate%601 type for a delegate that returns a test on a single value: -```cs +```csharp public delegate bool Predicate(T obj); ``` You may notice that for any `Predicate` type, a structurally equivalent `Func` type exists For example: -```cs +```csharp Func TestForString; Predicate AnotherTestForString; ``` diff --git a/docs/csharp/event-pattern.md b/docs/csharp/event-pattern.md index aeeb398d5ae05..464c9a9ef5678 100644 --- a/docs/csharp/event-pattern.md +++ b/docs/csharp/event-pattern.md @@ -28,7 +28,7 @@ subscribe and process standard events in your code. The standard signature for a .NET event delegate is: -```cs +```csharp void OnEventRaised(object sender, EventArgs args); ``` @@ -65,7 +65,7 @@ robust algorithms. Here is the initial event argument declaration for finding a sought file: -```cs +```csharp public class FileFoundArgs : EventArgs { public string FoundFile { get; } @@ -94,7 +94,7 @@ specialization. Let's fill out the FileSearcher class to search for files that match a pattern, and raise the correct event when a match is discovered. -```cs +```csharp public class FileSearcher { public event EventHandler FileFound; @@ -114,7 +114,7 @@ public class FileSearcher The simplest way to add an event to your class is to declare that event as a public field, as in the above example: -```cs +```csharp public event EventHandler FileFound; ``` @@ -125,7 +125,7 @@ practice, the code generated by the compiler does create wrappers so that the event objects can only be accessed in safe ways. The only operations available on a field-like event are add handler: -```cs +```csharp EventHandler onFileFound = (sender, eventArgs) => Console.WriteLine(eventArgs.FoundFile); lister.FileFound += onFIleFound; @@ -133,7 +133,7 @@ lister.FileFound += onFIleFound; and remove handler: -```cs +```csharp lister.FileFound -= onFileFound; ``` @@ -180,7 +180,7 @@ indicate a cancel incorrectly. Let's implement the first version for this sample. You need to add a boolean field to the FileFoundEventArgs type: -```cs +```csharp public class FileFoundArgs : EventArgs { public string FoundFile { get; } @@ -199,7 +199,7 @@ happens automatically. The only other change to the component is to check the flag after raising the event to see if any of the subscribers have requested a cancellation: -```cs +```csharp public void List(string directory, string searchPattern) { foreach (var file in Directory.EnumerateFiles(directory, searchPattern)) @@ -220,7 +220,7 @@ support the new cancel protocol. It's very loosely coupled. Let's update the subscriber so that it requests a cancellation once it finds the first executable: -```cs +```csharp EventHandler onFileFound = (sender, eventArgs) => { Console.WriteLine(eventArgs.FoundFile); @@ -244,7 +244,7 @@ can also make the types used for the arguments internal as well. You'll start by creating the new EventArgs derived class for reporting the new directory and progress. -```cs +```csharp internal class SearchDirectoryArgs : EventArgs { internal string CurrentSearchDirectory { get; } @@ -269,7 +269,7 @@ property, with add and remove handlers. In this sample, you won't need extra code in those handlers in this project, but this shows how you would create them. -```cs +```csharp internal event EventHandler DirectoryChanged { add { directoryChanged += value; } @@ -292,7 +292,7 @@ subdirectories and raises both events. The easiest way to accomplish this is to use a default argument to specify that you want to search all directories: -```cs +```csharp public void Search(string directory, string searchPattern, bool searchSubDirs = false) { if (searchSubDirs) @@ -338,7 +338,7 @@ that this works correctly. Let's add a handler to write a line that shows the progress in the console window. -```cs +```csharp lister.DirectoryChanged += (sender, eventArgs) => { Console.Write($"Entering '{eventArgs.CurrentSearchDirectory}'."); diff --git a/docs/csharp/events-overview.md b/docs/csharp/events-overview.md index 5537f4f3ecc61..85c211e6b25e3 100644 --- a/docs/csharp/events-overview.md +++ b/docs/csharp/events-overview.md @@ -64,7 +64,7 @@ an extension of the syntax for delegates. To define an event you use the `event` keyword: -```cs +```csharp public event EventHandler Progress; ``` @@ -87,7 +87,7 @@ argument. When you want to raise the event, you call the event handlers using the delegate invocation syntax: -```cs +```csharp Progress?.Invoke(this, new FileListArgs(file)); ``` @@ -97,7 +97,7 @@ when there are no subscribers to that event. You subscribe to an event by using the `+=` operator: -```cs +```csharp EventHandler onProgress = (sender, eventArgs) => Console.WriteLine(eventArgs.FoundFile); lister.Progress += OnProgress; @@ -108,7 +108,7 @@ by the event name, as shown above. You unsubscribe using the `-=` operator: -```cs +```csharp lister.Progress -= onProgress; ``` diff --git a/docs/csharp/expression-classes.md b/docs/csharp/expression-classes.md index 77f33cd4210ec..1bb10f340add1 100644 --- a/docs/csharp/expression-classes.md +++ b/docs/csharp/expression-classes.md @@ -46,7 +46,7 @@ expression. I've followed the practice of checking the node type, then casting to a variable access expression and then checking the properties of the specific expression type: -```cs +```csharp Expression> addFive = (num) => num + 5; if (addFive.NodeType == ExpressionType.Lambda) @@ -66,7 +66,7 @@ The `System.Linq.Expression` class also contains many static methods to create e methods create an expression node using the arguments supplied for its children. In this way, you build an expression up from its leaf nodes. For example, this code builds an Add expression: -```cs +```csharp // Addition is an add expression for "1 + 2" var one = Expression.Constant(1, typeof(int)); var two = Expression.Constant(2, typeof(int)); diff --git a/docs/csharp/expression-trees-building.md b/docs/csharp/expression-trees-building.md index bbcac783de615..16bfb46320ce7 100644 --- a/docs/csharp/expression-trees-building.md +++ b/docs/csharp/expression-trees-building.md @@ -35,7 +35,7 @@ a few examples to show you the techniques. Let's start relatively simply again. We'll use the addition expression I've been working with throughout these sections: -```cs +```csharp Expression> sum = () => 1 + 2; ``` @@ -43,21 +43,21 @@ To construct that expression tree, you must construct the leaf nodes. The leaf nodes are constants, so you can use the `Expression.Constant` method to create the nodes: -```cs +```csharp var one = Expression.Constant(1, typeof(int)); var two = Expression.Constant(2, typeof(int)); ``` Next, you'll build the addition expression: -```cs +```csharp var addition = Expression.Add(one, two); ``` Once you've got the addition expression, you can create the lambda expression: -```cs +```csharp var lamdba = Expression.Lambda(addition); ``` @@ -68,7 +68,7 @@ and build more complicated expressions. For expressions that are as simple as this one, you may combine all the calls into a single statement: -```cs +```csharp var lambda = Expression.Lambda( Expression.Add( Expression.Constant(1, typeof(int)), @@ -87,14 +87,14 @@ the argument nodes, and method call nodes. Let's build an expression tree to create this expression: -```cs +```csharp Expression> distanceCalc = (x, y) => Math.Sqrt(x * x + y * y); ``` You'll start by creating parameter expressions for `x` and `y`: -```cs +```csharp var xParameter = Expression.Parameter(typeof(double), "x"); var yParameter = Expression.Parameter(typeof(double), "y"); ``` @@ -102,7 +102,7 @@ var yParameter = Expression.Parameter(typeof(double), "y"); Creating the multiplication and addition expressions follows the pattern you've already seen: -```cs +```csharp var xSquared = Expression.Multiply(xParameter, xParameter); var ySquared = Expression.Multiply(yParameter, yParameter); var sum = Expression.Add(xSquared, ySquared); @@ -111,7 +111,7 @@ var sum = Expression.Add(xSquared, ySquared); Next, you need to create a method call expression for the call to `Math.Sqrt`. -```cs +```csharp var sqrtMethod = typeof(Math).GetMethod("Sqrt", new[] { typeof(double) }); var distance = Expression.Call(sqrtMethod, sum); ``` @@ -119,7 +119,7 @@ var distance = Expression.Call(sqrtMethod, sum); And then finally, you put the method call into a lambda expression, and make sure to define the arguments to the lambda expression: -```cs +```csharp var distanceLambda = Expression.Lambda( distance, xParameter, @@ -146,7 +146,7 @@ the code is to manage and to read. Let's build an expression tree that is the equivalent of this code: -```cs +```csharp Func factorialFunc = (n) => { var res = 1; @@ -165,7 +165,7 @@ to build the same functionality. It's complicated by the fact that there isn't a a `while` loop, instead you need to build a loop that contains a conditional test, and a label target to break out of the loop. -```cs +```csharp var nArgument = Expression.Parameter(typeof(int), "n"); var result = Expression.Variable(typeof(int), "result"); diff --git a/docs/csharp/expression-trees-execution.md b/docs/csharp/expression-trees-execution.md index 89b13c1bbeb06..eb89f36cf30ee 100644 --- a/docs/csharp/expression-trees-execution.md +++ b/docs/csharp/expression-trees-execution.md @@ -61,7 +61,7 @@ generated delegate. You would convert an expression into a delegate using the following code: -```cs +```csharp Expression> add = () => 1 + 2; var func = add.Compile(); // Create Delegate var answer = func(); // Invoke Delegate @@ -119,7 +119,7 @@ is still held by the expression tree. For example, this code works fine, because `int` does not implement `IDisposable`: -```cs +```csharp private static Func CreateBoundFunc() { var constant = 5; // constant is captured by the expression tree @@ -136,7 +136,7 @@ by `CreateBoundFunc` executes. However, consider this (rather contrived) class that implements `IDisposable`: -```cs +```csharp public class Resource : IDisposable { private bool isDisposed = false; @@ -161,7 +161,7 @@ If you use it in an expression as shown below, you'll get an `ObjectDisposedException` when you execute the code referenced by the `Resource.Argument` property: -```cs +```csharp private static Func CreateBoundResource() { using (var constant = new Resource()) // constant is captured by the expression tree diff --git a/docs/csharp/expression-trees-explained.md b/docs/csharp/expression-trees-explained.md index 268acd523cc9c..d755d98117a9e 100644 --- a/docs/csharp/expression-trees-explained.md +++ b/docs/csharp/expression-trees-explained.md @@ -28,7 +28,7 @@ Trees are based on a totally different set of classes and APIs than the Roslyn A Let's look at a simple example. Here's a line of code: -```cs +```csharp var sum = 1 + 2; ``` If you were to analyze this as an expression tree, the tree contains several nodes. @@ -58,7 +58,7 @@ each node in the tree to see the code that makes up the statement: This may look complicated, but it is very powerful. Following the same process, you can decompose much more complicated expressions. Consider this expression: -```cs +```csharp var finalAnswer = this.SecretSauceFuncion( currentState.createInterimResult(), currentState.createSecondValue(1, 2), decisionServer.considerFinalOptions("hello")) + diff --git a/docs/csharp/expression-trees-interpreting.md b/docs/csharp/expression-trees-interpreting.md index a7ef1f8705a52..8037f369aafe8 100644 --- a/docs/csharp/expression-trees-interpreting.md +++ b/docs/csharp/expression-trees-interpreting.md @@ -33,7 +33,7 @@ Let's start by visiting each node in a very simple expression tree. Here's the code that creates a constant expression and then examines its properties: -```cs +```csharp var constant = Expression.Constant(24, typeof(int)); Console.WriteLine($"This is a/an {constant.NodeType} expression type"); @@ -57,7 +57,7 @@ out some important properties about it. Here's that code: Let's start with the addition sample from the introduction to this section. -```cs +```csharp Expression> sum = () => 1 + 2; ``` @@ -74,7 +74,7 @@ type of the `LambdaExpression`. To examine each node in this expression, we'll need to recursively visit a number of nodes. Here's a simple first implementation: -```cs +```csharp Expression> addition = (a, b) => a + b; Console.WriteLine($"This expression is a {addition.NodeType} expression type"); @@ -120,7 +120,7 @@ Any node that has children requires us to visit those children and determine what that node is. Here's the cleaned up version that utilizes recursion to visit the addition operations: -```cs +```csharp // Base Visitor class: public abstract class Visitor { @@ -258,7 +258,7 @@ can visit and process many more different types of expressions. Let's try a more complicated example, yet still limit the node types to addition only: -```cs +```csharp Expression> sum = () => 1 + 2 + 3 + 4; ``` @@ -269,7 +269,7 @@ children, representing the left and right operands. There are several possible ways to construct a tree that could be correct: -```cs +```csharp Expression> sum1 = () => 1 + (2 + (3 + 4)); Expression> sum2 = () => ((1 + 2) + 3) + 4; @@ -295,7 +295,7 @@ value of `10`. The compiler performs all the addition and reduces the expression to its simplest form. Simply adding one variable in the expression is sufficient to see the original tree: -```cs +```csharp Expression> sum = (a) => 1 + a + 3 + 4; ``` @@ -336,7 +336,7 @@ and see what tree it represents. Here's an example of the `sum3` expression above (with an additional parameter to prevent the compiler from computing the constant): -```cs +```csharp Expression> sum3 = (a, b) => (1 + a) + (3 + b); ``` @@ -385,7 +385,7 @@ you've seen in this section only handles constant integers and the binary `+` operator. As a final sample, let's update the visitor to handle a more complicated expression. Let's make it work for this: -```cs +```csharp Expression> factorial = (n) => n == 0 ? 1 : @@ -414,7 +414,7 @@ the node type every time you reach your `default` clause. After a few iterations, you'll have seen each of the potential nodes. Then, you have all you need. The result would be something like this: -```cs +```csharp public static Visitor CreateFromExpression(Expression node) { switch(node.NodeType) @@ -442,7 +442,7 @@ public static Visitor CreateFromExpression(Expression node) The ConditionalVisitor and MethodCallVisitor process those two nodes: -```cs +```csharp public class ConditionalVisitor : Visitor { private readonly ConditionalExpression node; diff --git a/docs/csharp/expression-trees-translating.md b/docs/csharp/expression-trees-translating.md index 806f3cf9c28c0..5afc4b0d61a49 100644 --- a/docs/csharp/expression-trees-translating.md +++ b/docs/csharp/expression-trees-translating.md @@ -45,7 +45,7 @@ Here, once you find a constant node, you create a new multiplication node whose children are the original constant, and the constant `10`: -```cs +```csharp private static Expression ReplaceNodes(Expression original) { if (original.NodeType == ExpressionType.Constant) @@ -67,7 +67,7 @@ By replacing the original node with the substitute, a new tree is formed that contains our modifications. We can verify that by compiling and executing the replaced tree. -```cs +```csharp var one = Expression.Constant(1, typeof(int)); var two = Expression.Constant(2, typeof(int)); var addition = Expression.Add(one, two); @@ -103,7 +103,7 @@ that is simply the value of the constant expression. For an addition expression, the result is the sum of the left and right operands, once those trees have been traversed. -```cs +```csharp var one = Expression.Constant(1, typeof(int)); var two = Expression.Constant(2, typeof(int)); var three= Expression.Constant(3, typeof(int)); @@ -139,7 +139,7 @@ Let's make it easier to trace how the nodes are analyzed and how the sum is computed by travsersing the tree. Here's an updated version of the Aggregate method that includes quite a bit of tracing information: -```cs +```csharp private static int Aggregate(Expression exp) { if (exp.NodeType == ExpressionType.Constant) @@ -202,7 +202,7 @@ through the tree and finds the sum. Now, let's look at a different run, with the expression given by `sum1`: -```cs +```csharp Expression sum1 = () => 1 + (2 + (3 + 4)); ``` diff --git a/docs/csharp/getting-started/debugging-with-visual-studio-2017.md b/docs/csharp/getting-started/debugging-with-visual-studio-2017.md index 7923df5cf96bf..78d102c2ef39b 100644 --- a/docs/csharp/getting-started/debugging-with-visual-studio-2017.md +++ b/docs/csharp/getting-started/debugging-with-visual-studio-2017.md @@ -70,7 +70,7 @@ To set a conditional breakpoint and test what happens when the user fails to ent 1. In the text box that reads "e.g. x == 5", enter the following: - ```cs + ```csharp String.IsNullOrEmpty(name) ``` @@ -88,7 +88,7 @@ To set a conditional breakpoint and test what happens when the user fails to ent 1. Note that the value of the `name` variable is "", or [String.Empty](xref:System.String.Empty). Confirm this by entering the following statement in the **Immediate window**: - ```cs + ```csharp ? name == String.Empty ``` diff --git a/docs/csharp/getting-started/testing-library-with-visual-studio.md b/docs/csharp/getting-started/testing-library-with-visual-studio.md index b693c450d9ec3..923f6ad4f794e 100644 --- a/docs/csharp/getting-started/testing-library-with-visual-studio.md +++ b/docs/csharp/getting-started/testing-library-with-visual-studio.md @@ -96,7 +96,7 @@ Our test run had no failures, so let's change it slightly so that one of the tes 1. Modify the `words` array in the `TestDoesNotStartWithUpper` method to include the string "Error", so that the statement reads as follows: - ```cs + ```csharp string[] words = { "alphabet", "Error", "zebra", "abc", "αυτοκινητοβιομηχανία", "государство", "1234", ".", ";", " " }; ``` diff --git a/docs/csharp/getting-started/with-visual-studio.md b/docs/csharp/getting-started/with-visual-studio.md index 3f5bc26d634d2..5e2e862c73027 100644 --- a/docs/csharp/getting-started/with-visual-studio.md +++ b/docs/csharp/getting-started/with-visual-studio.md @@ -40,7 +40,7 @@ Let's begin by creating a simple "Hello World" console application. Here are the 4. Let's have our existing application pause before it closes the console window. Add the following code immediately after the call to the @System.Console.WriteLine(System.String) method: - ```cs + ```csharp Console.Write("Press any key to continue..."); Console.ReadKey(true); ``` diff --git a/docs/csharp/indexers.md b/docs/csharp/indexers.md index 9e2a209201dba..b39f0b4db3feb 100644 --- a/docs/csharp/indexers.md +++ b/docs/csharp/indexers.md @@ -25,7 +25,7 @@ of values. You access an indexer through a variable name and square brackets . You place the indexer arguments inside the brackets: -```cs +```csharp var item = someObject["key"]; someObject["AnotherKey"] = item; ``` @@ -34,7 +34,7 @@ You declare indexers using the `this` keyword as the property name, and declaring the arguments within square brackets. This declaration would match the usage shown in the previous paragraph: -```cs +```csharp public int this[string key] { get { return storage.Find(key); } @@ -94,7 +94,7 @@ this behavior. It reports on how many data points exist. It creates pages to hold sections of the data on demand. It removes pages from memory to make room for pages needed by more recent requests. -```cs +```csharp public class DataSamples { private class Page @@ -230,7 +230,7 @@ class that maps a command line option to an `Action` delegate, and an `ArgsProcessor` that uses the `ArgsActions` to execute each `Action` when it encounters that option. -```cs +```csharp public class ArgsProcessor { private readonly ArgsActions actions; @@ -292,7 +292,7 @@ is in the set, and the class's maxIterations value is returned. (The computer generated images popularized for the Mandelbrot set define colors for the number of iterations necessary to determine that a point is outside the set. -```cs +```csharp public class Mandelbrot { readonly private int maxIterations; @@ -334,7 +334,7 @@ of different types. Consider a program that manages historical temperature data. This indexer uses a city and a date to set or get the high and low temperatures for that location: -```cs +```csharp using DateMeasurements = System.Collections.Generic.Dictionary; using CityDataMeasurements = @@ -389,7 +389,7 @@ the underlying storage must use different core collection types. There are two parts of this code that may be unfamiliar to some developers. These two `using` statements: -```cs +```csharp using DateMeasurements = System.Collections.Generic.Dictionary; using CityDataMeasurements = System.Collections.Generic.Dictionary>; ``` diff --git a/docs/csharp/iterators.md b/docs/csharp/iterators.md index 78efc9ad7039f..38435e3d74c87 100644 --- a/docs/csharp/iterators.md +++ b/docs/csharp/iterators.md @@ -37,7 +37,7 @@ Enumerating a collection is simple: The `foreach` keyword enumerates a collection, executing the embedded statement once for each element in the collection: -```cs +```csharp foreach (var item in collection) { Console.WriteLine(item.ToString()); @@ -62,7 +62,7 @@ use the `yield return` contextual keywords to define an iterator method. You could write this method to produce the sequence of integers from 0 through 9: -```cs +```csharp public IEnumerable GetSingleDigitNumbers() { yield return 0; @@ -84,7 +84,7 @@ You can (and often do) use other language constructs to simplify the code of an iterator method. The method definition below produces the exact same sequence of numbers: -```cs +```csharp public IEnumerable GetSingleDigitNumbers() { int index = 0; @@ -96,7 +96,7 @@ public IEnumerable GetSingleDigitNumbers() You don't have to decide one or the other. You can have as many `yield return` statements as necessary to meet the needs of your method: -```cs +```csharp public IEnumerable GetSingleDigitNumbers() { int index = 0; @@ -117,7 +117,7 @@ sensors generate a very large stream of data. To get a feel for the data, you might write a method that samples every Nth data element. This small iterator method does the trick: -```cs +```csharp public static IEnumerable Sample(this IEnumerable sourceSequence, int interval) { int index = 0; @@ -133,7 +133,7 @@ There is one important restriction on iterator methods: you can't have both a `return` statement and a `yield return` statement in the same method. The following will not compile: -```cs +```csharp public IEnumerable GetSingleDigitNumbers() { int index = 0; @@ -154,7 +154,7 @@ multiple methods, some using `return`, and some using `yield return`. You can modify the last method slightly to use `yield return` everywhere: -```cs +```csharp public IEnumerable GetSingleDigitNumbers() { int index = 0; @@ -175,7 +175,7 @@ a situation where you might want to return an empty collection, or the first 5 odd numbers, based on a boolean argument. You could write that as these two methods: -```cs +```csharp public IEnumerable GetSingleDigitOddNumbers(bool getCollection) { if (getCollection == false) @@ -207,7 +207,7 @@ by not properly managing resources. The compiler translates the `foreach` loop shown in the first example into something similar to this construct: -```cs +```csharp IEnumerator enumerator = collection.GetEnumerator(); while (enumerator.MoveNext()) { @@ -219,7 +219,7 @@ while (enumerator.MoveNext()) The construct above represents the code generated by the C# compiler as of version 5 and above. Prior to version 5, the `item` variable had a different scope: -```cs +```csharp // C# versions 1 through 4: IEnumerator enumerator = collection.GetEnumerator(); int item = default(int); @@ -238,7 +238,7 @@ The exact code generated by the compiler is somewhat more complicated, and handles situations where the object returned by `GetEnumerator()` implements the `IDisposable` interface. The full expansion generates code more like this: -```cs +```csharp { var enumerator = collection.GetEnumerator(); try @@ -258,7 +258,7 @@ the `IDisposable` interface. The full expansion generates code more like this: The manner in which the enumerator is disposed of depends on the characteristics of the type of `enumerator`. In the general case, the `finally` clause expands to: -```cs +```csharp finally { (enumerator as IDisposable)?.Dispose(); @@ -268,7 +268,7 @@ finally However, if the type of `enumerator` is a sealed type and there is no implicit conversion from the type of `enumerator` to `IDisposable`, the `finally` clause expands to an empty block: -```cs +```csharp finally { } @@ -277,7 +277,7 @@ finally If there is an implicit conversion from the type of `enumerator` to `IDisposable`, and `enumerator` is a non-nullable value type, the `finally` clause expands to: -```cs +```csharp finally { ((IDisposable)enumerator).Dispose(); diff --git a/docs/csharp/lambda-expressions.md b/docs/csharp/lambda-expressions.md index bac8057f8b8d3..a2d5af1dd66ca 100644 --- a/docs/csharp/lambda-expressions.md +++ b/docs/csharp/lambda-expressions.md @@ -36,7 +36,7 @@ Or you can pass it directly as a method argument: A lambda expression with an expression on the right side of the => operator is called an *expression lambda*. Expression lambdas are used extensively in the construction of [expression trees](expression-trees.md). An expression lambda returns the result of the expression and takes the following basic form: -```cs +```csharp (input parameters) => expression ``` @@ -58,7 +58,7 @@ Note in the previous example that the body of an expression lambda can consist o A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces: -```cs +```csharp (input parameters) => { statement; } ``` diff --git a/docs/csharp/language-reference/compiler-messages/cs0015.md b/docs/csharp/language-reference/compiler-messages/cs0015.md index 2fefb0e73965b..23ed214483b87 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0015.md +++ b/docs/csharp/language-reference/compiler-messages/cs0015.md @@ -38,7 +38,7 @@ The name of type 'type' is too long The following sample generates CS0015: -```cs +```csharp // CS0015.cs // Remove a C from one of the namespace names or the class name to resolve the error by diff --git a/docs/csharp/language-reference/compiler-messages/cs0052.md b/docs/csharp/language-reference/compiler-messages/cs0052.md index 8e0760866e8ca..919e235f20897 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0052.md +++ b/docs/csharp/language-reference/compiler-messages/cs0052.md @@ -38,7 +38,7 @@ Inconsistent accessibility: field type 'type' is less accessible than field 'fie ## Example The following sample generates CS0052: -```cs +```csharp // CS0052.cs public class MyClass2 { diff --git a/docs/csharp/language-reference/compiler-messages/cs0103.md b/docs/csharp/language-reference/compiler-messages/cs0103.md index 436f776d940e5..d3e13580e37a1 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0103.md +++ b/docs/csharp/language-reference/compiler-messages/cs0103.md @@ -37,7 +37,7 @@ The name 'identifier' does not exist in the current context This error frequently occurs if you declare a variable in a loop or a `try` or `if` block and then attempt to access it from an enclosing code block or a separate code block, as shown in the following example. -```cs +```csharp using System; class MyClass1 @@ -63,7 +63,7 @@ class MyClass1 The following example resolves the error. -```cs +```csharp using System; diff --git a/docs/csharp/language-reference/compiler-messages/cs0163.md b/docs/csharp/language-reference/compiler-messages/cs0163.md index 9816f0bba9657..48d85baaddae2 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0163.md +++ b/docs/csharp/language-reference/compiler-messages/cs0163.md @@ -50,7 +50,7 @@ Control cannot fall through from one case label ('label') to another The following sample generates CS0163. -```cs +```csharp // CS0163.cs public class MyClass { diff --git a/docs/csharp/language-reference/compiler-messages/cs0165.md b/docs/csharp/language-reference/compiler-messages/cs0165.md index bbec2ebfe4009..c3e41286fc218 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0165.md +++ b/docs/csharp/language-reference/compiler-messages/cs0165.md @@ -40,7 +40,7 @@ Use of unassigned local variable 'name' ## Example The following sample generates CS0165: -```cs +```csharp // CS0165.cs using System; @@ -93,7 +93,7 @@ class MyClass2 ## Example Compiler error CS0165 can occur in recursive delegate definitions. You can avoid the error by defining the delegate in two statements so that the variable is not used before it is initialized. The following example demonstrates the error and the resolution. -```cs +```csharp class Program { delegate void Del(); diff --git a/docs/csharp/language-reference/compiler-messages/cs0173.md b/docs/csharp/language-reference/compiler-messages/cs0173.md index eb6a6d605956f..3e4e832e85f31 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0173.md +++ b/docs/csharp/language-reference/compiler-messages/cs0173.md @@ -40,7 +40,7 @@ Type of conditional expression cannot be determined because there is no implicit ## Example The following sample generates CS0173: -```cs +```csharp // CS0173.cs public class C {} @@ -84,7 +84,7 @@ public class MyClass ## Example The following code does not produce CS0173 in Visual Studio 2005, but does in later versions. -```cs +```csharp //cs0173_2.cs class M { diff --git a/docs/csharp/language-reference/compiler-messages/cs0246.md b/docs/csharp/language-reference/compiler-messages/cs0246.md index 361de5ee54d1b..d6450cb6e38ea 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0246.md +++ b/docs/csharp/language-reference/compiler-messages/cs0246.md @@ -50,7 +50,7 @@ The type or namespace name 'type/namespace' could not be found (are you missing - Did you use a *using alias directive* without fully qualifying the type name? A `using` alias directive does not use the `using` directives in the source code file to resolve types. The following example generates CS0246 because the type `List` is not fully qualified. The `using` directive for `System.Collections.Generic` does not prevent the error. - ```cs + ```csharp using System.Collections.Generic; // The following declaration generates CS0246. @@ -67,7 +67,7 @@ The type or namespace name 'type/namespace' could not be found (are you missing The following example generates CS0246 because a necessary `using` directive is missing. -```cs +```csharp // CS0246.cs //using System.Diagnostics; @@ -89,7 +89,7 @@ public class MyClass The following example causes CS0246 because an object of type `Type` was used where an actual type was expected. -```cs +```csharp // CS0246b.cs using System; diff --git a/docs/csharp/language-reference/compiler-messages/cs0260.md b/docs/csharp/language-reference/compiler-messages/cs0260.md index 1e4f0fd8ff0ab..e1700fab080c6 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0260.md +++ b/docs/csharp/language-reference/compiler-messages/cs0260.md @@ -39,7 +39,7 @@ Missing partial modifier on declaration of type 'type'; another partial declarat The following sample generates CS0260: -```cs +```csharp // CS0260.cs // You must mark both parts of the definition of class C // by using the partial keyword. diff --git a/docs/csharp/language-reference/compiler-messages/cs0266.md b/docs/csharp/language-reference/compiler-messages/cs0266.md index ff14c67c7dcb8..68175d45ca284 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0266.md +++ b/docs/csharp/language-reference/compiler-messages/cs0266.md @@ -37,7 +37,7 @@ Cannot implicitly convert type 'type1' to 'type2'. An explicit conversion exists The following code shows examples that generate CS0266. -```cs +```csharp // CS0266.cs class MyClass { diff --git a/docs/csharp/language-reference/compiler-messages/cs0269.md b/docs/csharp/language-reference/compiler-messages/cs0269.md index d806a376f9475..01f660f98882b 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0269.md +++ b/docs/csharp/language-reference/compiler-messages/cs0269.md @@ -38,7 +38,7 @@ Use of unassigned out parameter 'parameter' ## Example The following sample generates CS0269: -```cs +```csharp // CS0269.cs class C { @@ -69,7 +69,7 @@ class C ## Example This could also occur if the initialization of a variable occurs in a try block, which the compiler is unable to verify will execute successfully: -```cs +```csharp // CS0269b.cs class C { diff --git a/docs/csharp/language-reference/compiler-messages/cs0304.md b/docs/csharp/language-reference/compiler-messages/cs0304.md index d0b8bbfb44633..3947f5fcd4752 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0304.md +++ b/docs/csharp/language-reference/compiler-messages/cs0304.md @@ -35,7 +35,7 @@ Cannot create an instance of the variable type 'type' because it does not have t When you implement a generic class, and you want to use the `new` keyword to create a new instance of any type that is supplied for a type parameter `T`, you must apply the [new() constraint](../../../csharp/language-reference/keywords/new.md) to `T` in the class declaration, as shown in the following example. -```cs +```csharp class C where T : new() ``` @@ -43,7 +43,7 @@ class C where T : new() The following example generates CS0304. -```cs +```csharp // CS0304.cs // Compile with: /target:library. @@ -57,7 +57,7 @@ class C The `new` operator also is not allowed in methods of the class. -```cs +```csharp // Compile with: /target:library. class C @@ -73,7 +73,7 @@ class C To avoid the error, declare the class by using the `new()` constraint, as shown in the following example. -```cs +```csharp // Compile with: /target:library. class C where T : new() diff --git a/docs/csharp/language-reference/compiler-messages/cs0417.md b/docs/csharp/language-reference/compiler-messages/cs0417.md index 4ee3d648507e1..9f1d8823fafc3 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0417.md +++ b/docs/csharp/language-reference/compiler-messages/cs0417.md @@ -38,7 +38,7 @@ translation.priority.ht: ## Example The following example generates CS0417: -```cs +```csharp // CS0417 class ExampleClass where T : new() { diff --git a/docs/csharp/language-reference/compiler-messages/cs0445.md b/docs/csharp/language-reference/compiler-messages/cs0445.md index 0abea96d3c24a..556e01d193e41 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0445.md +++ b/docs/csharp/language-reference/compiler-messages/cs0445.md @@ -37,7 +37,7 @@ Cannot modify the result of an unboxing conversion The following code generates CS0455. -```cs +```csharp // CS0445.CS class UnboxingTest diff --git a/docs/csharp/language-reference/compiler-messages/cs0467.md b/docs/csharp/language-reference/compiler-messages/cs0467.md index aacff5b19ca94..82e70b71e1370 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0467.md +++ b/docs/csharp/language-reference/compiler-messages/cs0467.md @@ -39,7 +39,7 @@ Ambiguity between method 'method' and non-method 'non-method'.Using method group ## Example The following example generates CS0467. -```cs +```csharp // CS0467.cs interface IList { diff --git a/docs/csharp/language-reference/compiler-messages/cs0579.md b/docs/csharp/language-reference/compiler-messages/cs0579.md index f4005f91b8a3f..47969a659b33e 100644 --- a/docs/csharp/language-reference/compiler-messages/cs0579.md +++ b/docs/csharp/language-reference/compiler-messages/cs0579.md @@ -38,7 +38,7 @@ Duplicate 'attribute' attribute ## Example The following example generates CS0579. -```cs +```csharp // CS0579.cs using System; public class MyAttribute : Attribute diff --git a/docs/csharp/language-reference/compiler-messages/cs1009.md b/docs/csharp/language-reference/compiler-messages/cs1009.md index fed87dae27b69..df5d71db59b88 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1009.md +++ b/docs/csharp/language-reference/compiler-messages/cs1009.md @@ -37,7 +37,7 @@ Unrecognized escape sequence The following sample generates CS1009. -```cs +```csharp // CS1009-a.cs class MyClass { @@ -53,13 +53,13 @@ class MyClass A common cause of this error is using the backslash character in a file name, as the following example shows. -```cs +```csharp string filename = "c:\myFolder\myFile.txt"; ``` To resolve this error, use "\\\\" or the @-quoted string literal, as the following example shows. -```cs +```csharp // CS1009-b.cs class MyClass { diff --git a/docs/csharp/language-reference/compiler-messages/cs1019.md b/docs/csharp/language-reference/compiler-messages/cs1019.md index b800804fd4c85..f3d9c9979101f 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1019.md +++ b/docs/csharp/language-reference/compiler-messages/cs1019.md @@ -38,7 +38,7 @@ Overloadable unary operator expected A *unary operator* is an operator that operates on a single operand. For example, `++` is a unary operator. You can overload some unary operators by using the `operator` keyword and specifying a single parameter of the type that the operator operates on. For example, if you want to overload the operator `++` for a user-defined class `Temperature` so that you can write `Temperature++`, you can define it in this way: -```cs +```csharp public static Temperature operator ++ (Temperature temp) { temp.Degrees++; @@ -50,7 +50,7 @@ public static Temperature operator ++ (Temperature temp) The following code generates CS1019: -```cs +```csharp // CS1019.cs public class ii { diff --git a/docs/csharp/language-reference/compiler-messages/cs1061.md b/docs/csharp/language-reference/compiler-messages/cs1061.md index 35b0cd62cb938..a785b7f0428f7 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1061.md +++ b/docs/csharp/language-reference/compiler-messages/cs1061.md @@ -38,7 +38,7 @@ translation.priority.ht: ## Example The following example generates CS1061 because `TestClass1` does not have a `DisplaySomething` method. It does have a method that is called `WriteSomething`. Perhaps that is what the author of this source code meant to write. -```cs +```csharp // cs1061.cs public class TestClass1 { diff --git a/docs/csharp/language-reference/compiler-messages/cs1501.md b/docs/csharp/language-reference/compiler-messages/cs1501.md index 8ef5cbd70cc73..ed895840b34ec 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1501.md +++ b/docs/csharp/language-reference/compiler-messages/cs1501.md @@ -39,7 +39,7 @@ No overload for method 'method' takes 'number' arguments ## Example The following sample generates CS1501. -```cs +```csharp using System; namespace ConsoleApplication1 diff --git a/docs/csharp/language-reference/compiler-messages/cs1519.md b/docs/csharp/language-reference/compiler-messages/cs1519.md index 27afd1c03a371..53220bba343ff 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1519.md +++ b/docs/csharp/language-reference/compiler-messages/cs1519.md @@ -39,7 +39,7 @@ Invalid token 'token' in class, struct, or interface member declaration The following sample generates CS1519 in five places because tokens are placed in locations where they are not valid: -```cs +```csharp // CS1519.cs // Generates CS1519 because a class name cannot be a number: class Test 42 diff --git a/docs/csharp/language-reference/compiler-messages/cs1540.md b/docs/csharp/language-reference/compiler-messages/cs1540.md index 2eec3d1a3eda1..ee812b30a8afd 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1540.md +++ b/docs/csharp/language-reference/compiler-messages/cs1540.md @@ -38,7 +38,7 @@ Cannot access protected member 'member' via a qualifier of type 'type1'; the qua In the `Employee` class in the following example, `emp2` and `emp3` both have type `Person` at compile time, but `emp2` has type `Manager` at run time. Because `Employee` is not derived from `Manager`, it cannot access the protected members of the base class, `Person`, through an instance of the `Manager` class. The compiler cannot determine what the run-time type of the two `Person` objects will be. Therefore, both the call from `emp2` and the call from `emp3` cause compiler error CS1540. -```cs +```csharp using System; using System.Text; diff --git a/docs/csharp/language-reference/compiler-messages/cs1612.md b/docs/csharp/language-reference/compiler-messages/cs1612.md index 2eb093041e354..9b67b5ae8644d 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1612.md +++ b/docs/csharp/language-reference/compiler-messages/cs1612.md @@ -35,14 +35,14 @@ Cannot modify the return value of 'expression' because it is not a variable An attempt was made to modify a value type that is produced as the result of an intermediate expression but is not stored in a variable. This error can occur when you attempt to directly modify a struct in a generic collection, as shown in the following example: -```cs +```csharp List list = {…}; list[0].Name = "MyStruct42"; //CS1612 ``` To modify the struct, first assign it to a local variable, modify the variable, then assign the variable back to the item in the collection. -```cs +```csharp List list = {…}; MyStruct ms = list[0]; ms.Name = "MyStruct42"; @@ -58,7 +58,7 @@ list[0] = ms; ## Example CS1612 also occurs when you attempt to access the member of a struct through a property on an enclosing class that is returning the entire struct, as shown in the following example: -```cs +```csharp // CS1612.cs using System; diff --git a/docs/csharp/language-reference/compiler-messages/cs1705.md b/docs/csharp/language-reference/compiler-messages/cs1705.md index cadbcda3b88e1..a3e10ec748038 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1705.md +++ b/docs/csharp/language-reference/compiler-messages/cs1705.md @@ -48,7 +48,7 @@ Assembly 'AssemblyName1' uses 'TypeName' which has a higher version than referen The following code creates the first of the identical DLLs. For information about how to generate a key file, see [/keyfile (C# Compiler Options)](../../../csharp/language-reference/compiler-options/keyfile-compiler-option.md). -```cs +```csharp // CS1705a.cs // Compile by using the following command: @@ -68,7 +68,7 @@ public class Class1 ## Example The following code defines version 2.0 of the assembly, as specified by the attribute. -```cs +```csharp // CS1705b.cs // Compile by using the following command: @@ -89,7 +89,7 @@ public class Class1 ## Example The following code references the two DLL versions that are defined in the preceding code. `AssemblyA` refers to the DLL created by CS1705a.cs (version 1.0). `AssemblyB` refers to the DLL created by CS1705b.cs (version 2.0). In `ClassC`, two methods are defined. The first, `Return1A`, returns an object of type `Class1A`, which is an alias for `Class1` from version 1.0 of the DLL. The second, `Return1B`, returns an object of type `Class1B`, which is an alias for `Class1` from version 2.0 of the DLL. The definition of `Return1A` creates a dependency on version 1.0; the definition of `Return1B` creates a dependency on version 2.0. -```cs +```csharp // CS1705c.cs // Compile by using the following command. AssemblyA refers to the DLL created by @@ -132,7 +132,7 @@ public class ClassC ## Example The following code generates compiler error CS1705. It references the DLL created by CS1705a.cs (version 1.0). However, in the `Main` method, the code accesses `ClassC` from CS1705c.cs. `ClassC` uses a type that is defined in CS1705b.cs (version 2.0). This causes compiler error CS1705 because the type has a version number for CS1705.dll that is higher than the referenced version of CS1705.dll. -```cs +```csharp // CS1705d.cs // Compile by using the following command: diff --git a/docs/csharp/language-reference/compiler-messages/cs1708.md b/docs/csharp/language-reference/compiler-messages/cs1708.md index 239d4fc8b9628..9a366e54b6bcc 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1708.md +++ b/docs/csharp/language-reference/compiler-messages/cs1708.md @@ -41,7 +41,7 @@ Fixed size buffers can only be accessed through locals or fields ## Example The following sample generates CS1708. -```cs +```csharp // CS1708.cs // compile with: /unsafe using System; diff --git a/docs/csharp/language-reference/compiler-messages/cs1729.md b/docs/csharp/language-reference/compiler-messages/cs1729.md index 7d4507394a4b4..e5aa38ececfc8 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1729.md +++ b/docs/csharp/language-reference/compiler-messages/cs1729.md @@ -46,7 +46,7 @@ translation.priority.ht: ## Example The following example generates CS1729: -```cs +```csharp // cs1729.cs class Test { diff --git a/docs/csharp/language-reference/compiler-messages/cs1956.md b/docs/csharp/language-reference/compiler-messages/cs1956.md index a4e5b2f2f0381..f2a19af960e0d 100644 --- a/docs/csharp/language-reference/compiler-messages/cs1956.md +++ b/docs/csharp/language-reference/compiler-messages/cs1956.md @@ -44,7 +44,7 @@ Member 'name' implements interface member 'name' in type 'type'. There are multi ## Example The following code generates CS1956 because the two `Test` methods in `Base` differ only by the `ref`/`out` modifier on the first parameter. -```cs +```csharp // cs1956.cs class Base { diff --git a/docs/csharp/language-reference/compiler-messages/cs2032.md b/docs/csharp/language-reference/compiler-messages/cs2032.md index 0ed6c2d1c0f43..200039cbb9b8d 100644 --- a/docs/csharp/language-reference/compiler-messages/cs2032.md +++ b/docs/csharp/language-reference/compiler-messages/cs2032.md @@ -41,7 +41,7 @@ Character 'character' is not allowed on the command-line or in response files 1. In the **My Documents** folder, create a text file that is named CS2032.rsp, and then enter the following compiler options in it: - ```cs + ```csharp /target:exe /out:cs|2032.exe cs2032.cs ``` diff --git a/docs/csharp/language-reference/compiler-messages/cs4014.md b/docs/csharp/language-reference/compiler-messages/cs4014.md index 87d8eb873b121..4b22da70b31b8 100644 --- a/docs/csharp/language-reference/compiler-messages/cs4014.md +++ b/docs/csharp/language-reference/compiler-messages/cs4014.md @@ -44,7 +44,7 @@ Because this call is not awaited, execution of the current method continues befo The following example shows how to cause the warning, how to suppress it, and how to await the call. -```cs +```csharp async Task CallingMethodAsync() { @@ -122,7 +122,7 @@ Exiting the Click event handler. 3. Replace the code in the **XAML** view of MainWindow.xaml with the following code. - ```cs + ```csharp ExampleMethodAsync() { // . . . . @@ -58,7 +58,7 @@ string contents = await contentsTask; ## Example The following example shows the structure and flow of control between an async event handler, `StartButton_Click`, and an async method, `ExampleMethodAsync`. The result from the async method is the length of a downloaded website. The code is suitable for a Windows Presentation Foundation (WPF) app or Windows Store app that you create in [!INCLUDE[vs_dev12](../../../csharp/getting-started/includes/vs_dev12_md.md)]; see the code comments for setting up the app. -```cs +```csharp // You can run this code in Visual Studio 2013 as a WPF app or a Windows Store app. // You need a button (StartButton) and a textbox (ResultsTextBox). // Remember to set the names and handler so that you have something like this: diff --git a/docs/csharp/language-reference/keywords/await.md b/docs/csharp/language-reference/keywords/await.md index 496ceaadc3801..23aafeb7a7958 100644 --- a/docs/csharp/language-reference/keywords/await.md +++ b/docs/csharp/language-reference/keywords/await.md @@ -43,7 +43,7 @@ The `await` operator is applied to a task in an asynchronous method to suspend t In the following code, the method returns a `Task\`, `getContentsTask`. The task is a promise to produce the actual byte array when the task is complete. The `await` operator is applied to `getContentsTask` to suspend execution in `SumPageSizesAsync` until `getContentsTask` is complete. In the meantime, control is returned to the caller of `SumPageSizesAsync`. When `getContentsTask` is finished, the `await` expression evaluates to a byte array. -```cs +```csharp private async Task SumPageSizesAsync() { @@ -66,7 +66,7 @@ private async Task SumPageSizesAsync() As shown in the previous example, if `await` is applied to the result of a method call that returns a `Task`, then the type of the `await` expression is TResult. If `await` is applied to the result of a method call that returns a `Task`, then the type of the `await` expression is void. The following example illustrates the difference. -```cs +```csharp // Keyword await used with a method that returns a Task. TResult result = await AsyncMethodThatReturnsTaskTResult(); @@ -93,7 +93,7 @@ await AsyncMethodThatReturnsTask(); ## Example The following Windows Forms example illustrates the use of `await` in an async method, `WaitAsynchronouslyAsync`. Contrast the behavior of that method with the behavior of `WaitSynchronously`. Without an `await` operator applied to a task, `WaitSynchronously` runs synchronously despite the use of the `async` modifier in its definition and a call to in its body. -```cs +```csharp private async void button1_Click(object sender, EventArgs e) { diff --git a/docs/csharp/language-reference/keywords/decimal.md b/docs/csharp/language-reference/keywords/decimal.md index cc4da8ad11617..c884e7b45f365 100644 --- a/docs/csharp/language-reference/keywords/decimal.md +++ b/docs/csharp/language-reference/keywords/decimal.md @@ -77,7 +77,7 @@ myMoney = (decimal)x; ## Example The following example causes a compiler error by trying to add [double](../../../csharp/language-reference/keywords/double.md) and `decimal` variables. -```cs +```csharp double dub = 9; // The following line causes an error that reads "Operator '+' cannot be applied to // operands of type 'double' and 'decimal'" diff --git a/docs/csharp/language-reference/keywords/dynamic.md b/docs/csharp/language-reference/keywords/dynamic.md index 099bed9f283d3..8f72d1a986363 100644 --- a/docs/csharp/language-reference/keywords/dynamic.md +++ b/docs/csharp/language-reference/keywords/dynamic.md @@ -48,7 +48,7 @@ The `dynamic` type enables the operations in which it occurs to bypass compile-t To see the difference between `dyn` and `obj` at compile time, add the following two lines between the declarations and the `WriteLine` statements in the previous example. -```cs +```csharp dyn = dyn + 3; obj = obj + 3; ``` diff --git a/docs/csharp/language-reference/keywords/fixed-statement.md b/docs/csharp/language-reference/keywords/fixed-statement.md index 38a51891d12d4..20face37880ad 100644 --- a/docs/csharp/language-reference/keywords/fixed-statement.md +++ b/docs/csharp/language-reference/keywords/fixed-statement.md @@ -44,7 +44,7 @@ The `fixed` statement prevents the garbage collector from relocating a movable v You can initialize multiple pointers, as long as they are all of the same type. -```cs +```csharp fixed (byte* ps = srcarray, pd = dstarray) {...} ``` diff --git a/docs/csharp/language-reference/keywords/float.md b/docs/csharp/language-reference/keywords/float.md index f0347476e616f..92b854bda792e 100644 --- a/docs/csharp/language-reference/keywords/float.md +++ b/docs/csharp/language-reference/keywords/float.md @@ -42,7 +42,7 @@ The `float` keyword signifies a simple type that stores 32-bit floating-point va ## Literals By default, a real numeric literal on the right side of the assignment operator is treated as [double](double.md). Therefore, to initialize a float variable, use the suffix `f` or `F`, as in the following example: -```cs +```csharp float x = 3.5F; ``` diff --git a/docs/csharp/language-reference/keywords/for.md b/docs/csharp/language-reference/keywords/for.md index 4cdcfaaad292a..6816864558bec 100644 --- a/docs/csharp/language-reference/keywords/for.md +++ b/docs/csharp/language-reference/keywords/for.md @@ -59,7 +59,7 @@ By using a `for` loop, you can run a statement or a block of statements repeated Every `for` statement defines initializer, condition, and iterator sections. These sections usually determine how many times the loop iterates. -```cs +```csharp for (initializer; condition; iterator) body ``` diff --git a/docs/csharp/language-reference/keywords/group-clause.md b/docs/csharp/language-reference/keywords/group-clause.md index 6b55d044bd2ed..e18430f8eb9d5 100644 --- a/docs/csharp/language-reference/keywords/group-clause.md +++ b/docs/csharp/language-reference/keywords/group-clause.md @@ -71,7 +71,7 @@ The `group` clause returns a sequence of object ### Grouping by Composite Keys Use a composite key when you want to group elements according to more than one key. You create a composite key by using an anonymous type or a named type to hold the key element. In the following example, assume that a class `Person` has been declared with members named `surname` and `city`. The `group` clause causes a separate group to be created for each set of persons with the same last name and the same city. -```cs +```csharp group person by new {name = person.surname, city = person.city}; ``` diff --git a/docs/csharp/language-reference/keywords/if-else.md b/docs/csharp/language-reference/keywords/if-else.md index 30b576bf0fc74..78dd4bda05c7c 100644 --- a/docs/csharp/language-reference/keywords/if-else.md +++ b/docs/csharp/language-reference/keywords/if-else.md @@ -44,7 +44,7 @@ An `if` statement identifies which statement to run based on the value of a `Boo An `if` statement in C# can take two forms, as the following example shows. -```cs +```csharp // if-else statement if (condition) @@ -98,7 +98,7 @@ if (condition) Just as a statement in the else block or the then block can be any valid statement, you can use any valid Boolean expression for the condition. You can use logical operators such as [&&](../../../csharp/language-reference/operators/conditional-and-operator.md), [&](../../../csharp/language-reference/operators/and-operator.md), [||](../../../csharp/language-reference/operators/conditional-or-operator.md), [|](../../../csharp/language-reference/operators/or-operator.md) and [!](../../../csharp/language-reference/operators/logical-negation-operator.md) to make compound conditions. The following code shows examples. -```cs +```csharp // NOT bool result = true; if (!result) diff --git a/docs/csharp/language-reference/keywords/int.md b/docs/csharp/language-reference/keywords/int.md index 6a1aaf4a76b95..e25cba3aa3052 100644 --- a/docs/csharp/language-reference/keywords/int.md +++ b/docs/csharp/language-reference/keywords/int.md @@ -66,14 +66,14 @@ In these examples, the literal 90946 is of type `int`. ## Conversions There is a predefined implicit conversion from `int` to [long](../../../csharp/language-reference/keywords/long.md), [float](../../../csharp/language-reference/keywords/float.md), [double](../../../csharp/language-reference/keywords/double.md), or [decimal](../../../csharp/language-reference/keywords/decimal.md). For example: -```cs +```csharp // '123' is an int, so an implicit conversion takes place here: float f = 123; ``` There is a predefined implicit conversion from [sbyte](../../../csharp/language-reference/keywords/sbyte.md), [byte](../../../csharp/language-reference/keywords/byte.md), [short](../../../csharp/language-reference/keywords/short.md), [ushort](../../../csharp/language-reference/keywords/ushort.md), or [char](../../../csharp/language-reference/keywords/char.md) to `int`. For example, the following assignment statement will produce a compilation error without a cast: -```cs +```csharp long aLong = 22; int i1 = aLong; // Error: no implicit conversion from long. int i2 = (int)aLong; // OK: explicit conversion. @@ -81,7 +81,7 @@ int i2 = (int)aLong; // OK: explicit conversion. Notice also that there is no implicit conversion from floating-point types to `int`. For example, the following statement generates a compiler error unless an explicit cast is used: -```cs +```csharp int x = 3.0; // Error: no implicit conversion from double. int y = (int)3.0; // OK: explicit conversion. ``` diff --git a/docs/csharp/language-reference/keywords/interpolated-strings.md b/docs/csharp/language-reference/keywords/interpolated-strings.md index 66ee9bdda7604..3f3c75026f2ab 100644 --- a/docs/csharp/language-reference/keywords/interpolated-strings.md +++ b/docs/csharp/language-reference/keywords/interpolated-strings.md @@ -33,12 +33,12 @@ Used to construct strings. An interpolated string looks like a template string The arguments of an interpolated string are easier to understand than a [composite format string](../../../standard/base-types/composite-format.md#composite-format-string). For example, the interpolated string -```cs +```csharp Console.WriteLine($"Name = {name}, hours = {hours:hh}"); ``` contains two interpolated expressions, '{name}' and '{hours:hh}'. The equivalent composite format string is: -```cs +```csharp Console.WriteLine("Name = {0}, hours = {1:hh}", name, hours); ``` diff --git a/docs/csharp/language-reference/keywords/is.md b/docs/csharp/language-reference/keywords/is.md index 4005a2759d28e..20866d3c71bc2 100644 --- a/docs/csharp/language-reference/keywords/is.md +++ b/docs/csharp/language-reference/keywords/is.md @@ -40,7 +40,7 @@ Checks if an object is compatible with a given type, or (starting with C# 7) tes The `is` keyword evaluates type compatibility at runtime. It determines whether an object instance or the result of an expression can be converted to a specified type. It has the syntax -```cs +```csharp expr is type ``` @@ -87,7 +87,7 @@ Starting with C# 7, the `is` and [switch](../../../csharp/language-reference/key When using the type pattern to perform pattern matching, `is` tests whether an expression can be converted to a specified type and, if it can be, casts it to a variable of that type. It is a straightforward extension of the `is` statement that enables concise type evaluation and conversion. The general form of the `is` type pattern is: -```cs +```csharp expr is type varname ``` @@ -125,7 +125,7 @@ The equivalent code without pattern matching requires a separate assignment that When performing pattern matching with the constant pattern, `is` tests whether an expression equals a specified constant. In C# 6 and earlier versions, the constant pattern is supported by the [switch](switch.md) statement. Starting with C# 7, it is supported by the `is` statement as well. Its syntax is: -```cs +```csharp expr is constant ``` @@ -151,7 +151,7 @@ The following example combines the type and constant patterns to test whether an A pattern match with the var pattern always succeeds. Its syntax is -```cs +```csharp expr is var varname ``` diff --git a/docs/csharp/language-reference/keywords/long.md b/docs/csharp/language-reference/keywords/long.md index 594b16cc7d57e..7df4e73b536e5 100644 --- a/docs/csharp/language-reference/keywords/long.md +++ b/docs/csharp/language-reference/keywords/long.md @@ -56,7 +56,7 @@ Starting with C# 7, you can also use the underscore character, `_`, as a digit s Integer literals can also include a suffix that denotes the type. The suffix `L` denotes a `long`. The following example uses the `L` suffix to denote a long integer: -```cs +```csharp long value = 4294967296L; ``` @@ -67,14 +67,14 @@ long value = 4294967296L; A common use of the suffix is to call overloaded methods. For example, the following overloaded methods have parameters of type `long` and [int](../../../csharp/language-reference/keywords/int.md): -```cs +```csharp public static void SampleMethod(int i) {} public static void SampleMethod(long l) {} ``` The `L` suffix guarantees that the correct overload is called: -```cs +```csharp SampleMethod(5); // Calls the method with the int parameter SampleMethod(5L); // Calls the method with the long parameter ``` @@ -89,7 +89,7 @@ The literal 4294967296 in the previous examples is of type `long`, because it ex If you use the `long` type with other integral types in the same expression, the expression is evaluated as `long` (or [bool](../../../csharp/language-reference/keywords/bool.md) in the case of relational or Boolean expressions). For example, the following expression evaluates as `long`: -```cs +```csharp 898L + 88 ``` @@ -98,7 +98,7 @@ The literal 4294967296 in the previous examples is of type `long`, because it ex ## Conversions There is a predefined implicit conversion from `long` to [float](../../../csharp/language-reference/keywords/float.md), [double](../../../csharp/language-reference/keywords/double.md), or [decimal](../../../csharp/language-reference/keywords/decimal.md). Otherwise a cast must be used. For example, the following statement will produce a compilation error without an explicit cast: -```cs +```csharp int x = 8L; // Error: no implicit conversion from long to int int x = (int)8L; // OK: explicit conversion to int ``` @@ -107,7 +107,7 @@ int x = (int)8L; // OK: explicit conversion to int Notice also that there is no implicit conversion from floating-point types to `long`. For example, the following statement generates a compiler error unless an explicit cast is used: -```cs +```csharp long x = 3.0; // Error: no implicit conversion from double long y = (long)3.0; // OK: explicit conversion ``` diff --git a/docs/csharp/language-reference/keywords/nameof.md b/docs/csharp/language-reference/keywords/nameof.md index fd7faa70b4dc8..45fed9ad21bc2 100644 --- a/docs/csharp/language-reference/keywords/nameof.md +++ b/docs/csharp/language-reference/keywords/nameof.md @@ -37,7 +37,7 @@ When reporting errors in code, hooking up model-view-controller (MVC) links, fir A `nameof` expression has this form: -```cs +```csharp if (x == null) throw new ArgumentNullException(nameof(x)); WriteLine(nameof(person.Address.ZipCode)); // prints "ZipCode” @@ -47,7 +47,7 @@ WriteLine(nameof(person.Address.ZipCode)); // prints "ZipCode” These examples show the key use cases for `nameof`. Validate parameters: - ```cs + ```csharp void f(string s) { if (s == null) throw new ArgumentNullException(nameof(s)); } @@ -64,7 +64,7 @@ void f(string s) { ``` INotifyPropertyChanged: - ```cs + ```csharp int p { get { return this.p; } set { this.p = value; PropertyChanged(this, new PropertyChangedEventArgs(nameof(this.p)); } // nameof(p) works too @@ -73,13 +73,13 @@ int p { ``` XAML dependency property: - ```cs + ```csharp public static DependencyProperty AgeProperty = DependencyProperty.Register(nameof(Age), typeof(int), typeof(C)); ``` Logging: - ```cs + ```csharp void f(int i) { Log(nameof(f), "method entry"); } @@ -87,7 +87,7 @@ void f(int i) { ``` Attributes: - ```cs + ```csharp [DebuggerDisplay("={" + nameof(GetString) + "()}")] class C { string GetString() { } @@ -97,7 +97,7 @@ class C { ## Examples Some C# examples: -```cs +```csharp using Stuff = Some.Cool.Functionality class C { static int Method1 (string x, int y) {} diff --git a/docs/csharp/language-reference/keywords/out-parameter-modifier.md b/docs/csharp/language-reference/keywords/out-parameter-modifier.md index 43a4cb5aa90f4..2942e1cbfa437 100644 --- a/docs/csharp/language-reference/keywords/out-parameter-modifier.md +++ b/docs/csharp/language-reference/keywords/out-parameter-modifier.md @@ -41,7 +41,7 @@ The `out` keyword causes arguments to be passed by reference. It is like the [re Although the `ref` and `out` keywords cause different run-time behavior, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a `ref` argument and the other takes an `out` argument. The following code, for example, will not compile: -```cs +```csharp class CS0663_Example { // Compiler error CS0663: "Cannot define overloaded diff --git a/docs/csharp/language-reference/keywords/sbyte.md b/docs/csharp/language-reference/keywords/sbyte.md index 0dc9900f0ddbc..04467e4cea85e 100644 --- a/docs/csharp/language-reference/keywords/sbyte.md +++ b/docs/csharp/language-reference/keywords/sbyte.md @@ -60,14 +60,14 @@ If the integer literal is outside the range of `sbyte` (that is, if it is less t A cast must be used when calling overloaded methods. Consider, for example, the following overloaded methods that use `sbyte` and [int](../../../csharp/language-reference/keywords/int.md) parameters: -```cs +```csharp public static void SampleMethod(int i) {} public static void SampleMethod(sbyte b) {} ``` Using the `sbyte` cast guarantees that the correct type is called, for example: -```cs +```csharp // Calling the method with the int parameter: SampleMethod(5); // Calling the method with the sbyte parameter: @@ -79,25 +79,25 @@ SampleMethod((sbyte)5); You cannot implicitly convert nonliteral numeric types of larger storage size to `sbyte` (see [Integral Types Table](../../../csharp/language-reference/keywords/integral-types-table.md) for the storage sizes of integral types). Consider, for example, the following two `sbyte` variables `x` and `y`: -```cs +```csharp sbyte x = 10, y = 20; ``` The following assignment statement will produce a compilation error, because the arithmetic expression on the right side of the assignment operator evaluates to [int](../../../csharp/language-reference/keywords/int.md) by default. -```cs +```csharp sbyte z = x + y; // Error: conversion from int to sbyte ``` To fix this problem, cast the expression as in the following example: -```cs +```csharp sbyte z = (sbyte)(x + y); // OK: explicit conversion ``` It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size: -```cs +```csharp sbyte x = 10, y = 20; int m = x + y; long n = x + y; @@ -105,7 +105,7 @@ long n = x + y; Notice also that there is no implicit conversion from floating-point types to `sbyte`. For example, the following statement generates a compiler error unless an explicit cast is used: -```cs +```csharp sbyte x = 3.0; // Error: no implicit conversion from double sbyte y = (sbyte)3.0; // OK: explicit conversion ``` diff --git a/docs/csharp/language-reference/keywords/short.md b/docs/csharp/language-reference/keywords/short.md index 85de65ea632ec..9242214eef1d1 100644 --- a/docs/csharp/language-reference/keywords/short.md +++ b/docs/csharp/language-reference/keywords/short.md @@ -58,14 +58,14 @@ Starting with C# 7, you can also use the underscore character, `_`, as a digit s A cast must be used when calling overloaded methods. Consider, for example, the following overloaded methods that use `short` and [int](../../../csharp/language-reference/keywords/int.md) parameters: -```cs +```csharp public static void SampleMethod(int i) {} public static void SampleMethod(short s) {} ``` Using the `short` cast guarantees that the correct type is called, for example: -```cs +```csharp SampleMethod(5); // Calling the method with the int parameter SampleMethod((short)5); // Calling the method with the short parameter ``` @@ -76,32 +76,32 @@ SampleMethod((short)5); // Calling the method with the short parameter You cannot implicitly convert nonliteral numeric types of larger storage size to `short` (see [Integral Types Table](../../../csharp/language-reference/keywords/integral-types-table.md) for the storage sizes of integral types). Consider, for example, the following two `short` variables `x` and `y`: -```cs +```csharp short x = 5, y = 12; ``` The following assignment statement produces a compilation error because the arithmetic expression on the right-hand side of the assignment operator evaluates to [int](../../../csharp/language-reference/keywords/int.md) by default. -```cs +```csharp short z = x + y; // Compiler error CS0266: no conversion from int to short ``` To fix this problem, use a cast: -```cs +```csharp short z = (short)(x + y); // Explicit conversion ``` It is also possible to use the following statements, where the destination variable has the same storage size or a larger storage size: -```cs +```csharp int m = x + y; long n = x + y; ``` There is no implicit conversion from floating-point types to `short`. For example, the following statement generates a compiler error unless an explicit cast is used: -```cs +```csharp short x = 3.0; // Error: no implicit conversion from double short y = (short)3.0; // OK: explicit conversion ``` diff --git a/docs/csharp/language-reference/keywords/sizeof.md b/docs/csharp/language-reference/keywords/sizeof.md index 803cc8c15d7c1..43b0dccd4d7a1 100644 --- a/docs/csharp/language-reference/keywords/sizeof.md +++ b/docs/csharp/language-reference/keywords/sizeof.md @@ -42,7 +42,7 @@ Used to obtain the size in bytes for an unmanaged type. Unmanaged types include The following example shows how to retrieve the size of an `int`: -```cs +```csharp // Constant value 4: int intSize = sizeof(int); ``` diff --git a/docs/csharp/language-reference/keywords/static.md b/docs/csharp/language-reference/keywords/static.md index 725dc85293eca..542f0e67bd18f 100644 --- a/docs/csharp/language-reference/keywords/static.md +++ b/docs/csharp/language-reference/keywords/static.md @@ -47,7 +47,7 @@ Use the `static` modifier to declare a static member, which belongs to the type To refer to the static member `x`, use the fully qualified name, `MyBaseC.MyStruct.x`, unless the member is accessible from the same scope: -```cs +```csharp Console.WriteLine(MyBaseC.MyStruct.x); ``` diff --git a/docs/csharp/language-reference/keywords/string.md b/docs/csharp/language-reference/keywords/string.md index d82d0a3fdecde..ebb57d20304f7 100644 --- a/docs/csharp/language-reference/keywords/string.md +++ b/docs/csharp/language-reference/keywords/string.md @@ -40,7 +40,7 @@ The `string` type represents a sequence of zero or more Unicode characters. `str Although `string` is a reference type, the equality operators (`==` and `!=`) are defined to compare the values of `string` objects, not references. This makes testing for string equality more intuitive. For example: -```cs +```csharp string a = "hello"; string b = "h"; @@ -54,7 +54,7 @@ Console.WriteLine((object)a == (object)b); The + operator concatenates strings: -```cs +```csharp string a = "good " + "morning"; ``` @@ -63,7 +63,7 @@ string a = "good " + "morning"; Strings are *immutable*--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection. -```cs +```csharp string b = "h"; b += "ello"; @@ -71,7 +71,7 @@ b += "ello"; The [] operator can be used for readonly access to individual characters of a `string`: -```cs +```csharp string str = "test"; char x = str[2]; // x = 's'; @@ -79,7 +79,7 @@ char x = str[2]; // x = 's'; String literals are of type `string` and can be written in two forms, quoted and @-quoted. Quoted string literals are enclosed in double quotation marks ("): -```cs +```csharp "good morning" // a string literal ``` @@ -96,19 +96,19 @@ Console.WriteLine(a); Verbatim string literals start with @ and are also enclosed in double quotation marks. For example: -```cs +```csharp @"good morning" // a string literal ``` The advantage of verbatim strings is that escape sequences are *not* processed, which makes it easy to write, for example, a fully qualified file name: -```cs +```csharp @"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt" ``` To include a double quotation mark in an @-quoted string, double it: -```cs +```csharp @"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain. ``` diff --git a/docs/csharp/language-reference/keywords/switch.md b/docs/csharp/language-reference/keywords/switch.md index f19032ab5022e..6d29c333525fa 100644 --- a/docs/csharp/language-reference/keywords/switch.md +++ b/docs/csharp/language-reference/keywords/switch.md @@ -54,7 +54,7 @@ It is equivalent to the following example that uses an `if`-`else` construct. The match expression provides the value to match against the patterns in `case` labels. Its syntax is: -```cs +```csharp switch (expr) ``` @@ -78,7 +78,7 @@ Starting with C# 7, the match expression can be any non-null expression. Only one switch section in a switch statement executes. C# does not allow execution to continue from one switch section to the next. Because of this, the following code generates a compiler error, CS0163: "Control cannot fall through from one case label () to another." -```cs +```csharp switch (caseSwitch) { // The following switch section causes an error. @@ -130,7 +130,7 @@ Each `case` statement defines a pattern that, if it matches the match expression The constant pattern tests whether the match expression equals a specified constant. Its syntax is: -```cs +```csharp case constant: ``` @@ -161,7 +161,7 @@ The following example uses the constant pattern to handle user input in a consol The type pattern enables concise type evaluation and conversion. When used with the `switch` statement to perform pattern matching, it tests whether an expression can be converted to a specified type and, if it can be, casts it to a variable of that type. Its syntax is: -```cs +```csharp case type varname ``` where *type* is the name of the type to which the result of *expr* is to be converted, and *varname* is the object to which the result of *expr* is converted if the match succeeds. @@ -180,7 +180,7 @@ If the case expression is true, *varname* is definitely assigned and has local s Note that `null` does not match a type. To match a `null`, you use the following `case` label: -```cs +```csharp case null: ``` diff --git a/docs/csharp/language-reference/keywords/throw.md b/docs/csharp/language-reference/keywords/throw.md index e85ff4e35abbf..fa3c0e30d91aa 100644 --- a/docs/csharp/language-reference/keywords/throw.md +++ b/docs/csharp/language-reference/keywords/throw.md @@ -40,7 +40,7 @@ Signals the occurrence of an exception during program execution. The syntax of `throw` is: -```cs +```csharp throw [e] ``` where `e` is an instance of a class derived from . The following example uses the `throw` statement to throw an @System.IndexOutOfRangeException if the argument passed to a method named `GetNumber` does not correspond to a valid index of an internal array. diff --git a/docs/csharp/language-reference/keywords/try-catch.md b/docs/csharp/language-reference/keywords/try-catch.md index 818abbe35d439..bc7904fe11ed8 100644 --- a/docs/csharp/language-reference/keywords/try-catch.md +++ b/docs/csharp/language-reference/keywords/try-catch.md @@ -43,7 +43,7 @@ The try-catch statement consists of a `try` block followed by one or more `catch The `try` block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully. For example, the following attempt to cast a `null` object raises the exception: -```cs +```csharp object o2 = null; try { @@ -53,7 +53,7 @@ try Although the `catch` clause can be used without arguments to catch any type of exception, this usage is not recommended. In general, you should only catch those exceptions that you know how to recover from. Therefore, you should always specify an object argument derived from For example: -```cs +```csharp catch (InvalidCastException e) { } @@ -63,7 +63,7 @@ catch (InvalidCastException e) Using `catch` arguments is one way to filter for the exceptions you want to handle. You can also use a predicate expression that further examines the exception to decide whether to handle it. If the predicate expression returns false, then the search for a handler continues. -```cs +```csharp catch (ArgumentException e) when (e.ParamName == “…”) { } @@ -73,7 +73,7 @@ catch (ArgumentException e) when (e.ParamName == “…”) A [throw](../../../csharp/language-reference/keywords/throw.md) statement can be used in a `catch` block to re-throw the exception that is caught by the `catch` statement. The following example extracts source information from an exception, and then throws the exception to the parent method. -```cs +```csharp catch (FileNotFoundException e) {     // FileNotFoundExceptions are handled here. @@ -90,7 +90,7 @@ catch (IOException e) You can catch one exception and throw a different exception. When you do this, specify the exception that you caught as the inner exception, as shown in the following example. -```cs +```csharp catch (InvalidCastException e) { // Perform some action here, and then throw a new exception. @@ -100,7 +100,7 @@ catch (InvalidCastException e) You can also re-throw an exception when a specified condition is true, as shown in the following example. -```cs +```csharp catch (InvalidCastException e) { @@ -117,7 +117,7 @@ catch (InvalidCastException e) From inside a `try` block, initialize only variables that are declared therein. Otherwise, an exception can occur before the execution of the block is completed. For example, in the following code example, the variable `n` is initialized inside the `try` block. An attempt to use this variable outside the `try` block in the `Write(n)` statement will generate a compiler error. -```cs +```csharp static void Main() { int n; diff --git a/docs/csharp/language-reference/keywords/uint.md b/docs/csharp/language-reference/keywords/uint.md index 74d92c1932e13..97d64eed50fb5 100644 --- a/docs/csharp/language-reference/keywords/uint.md +++ b/docs/csharp/language-reference/keywords/uint.md @@ -70,13 +70,13 @@ If an integer literal has no suffix, its type is the first of the following type ## Conversions There is a predefined implicit conversion from `uint` to [long](../../../csharp/language-reference/keywords/long.md), [ulong](../../../csharp/language-reference/keywords/ulong.md), [float](../../../csharp/language-reference/keywords/float.md), [double](../../../csharp/language-reference/keywords/double.md), or [decimal](../../../csharp/language-reference/keywords/decimal.md). For example: -```cs +```csharp float myFloat = 4294967290; // OK: implicit conversion to float ``` There is a predefined implicit conversion from [byte](../../../csharp/language-reference/keywords/byte.md), [ushort](../../../csharp/language-reference/keywords/ushort.md), or [char](../../../csharp/language-reference/keywords/char.md) to `uint`. Otherwise you must use a cast. For example, the following assignment statement will produce a compilation error without a cast: -```cs +```csharp long aLong = 22; // Error -- no implicit conversion from long: uint uInt1 = aLong; @@ -86,7 +86,7 @@ uint uInt2 = (uint)aLong; Notice also that there is no implicit conversion from floating-point types to `uint`. For example, the following statement generates a compiler error unless an explicit cast is used: -```cs +```csharp // Error -- no implicit conversion from double: uint x = 3.0; // OK -- explicit conversion: diff --git a/docs/csharp/language-reference/keywords/ulong.md b/docs/csharp/language-reference/keywords/ulong.md index 62dc2849764cf..425015d803cef 100644 --- a/docs/csharp/language-reference/keywords/ulong.md +++ b/docs/csharp/language-reference/keywords/ulong.md @@ -69,14 +69,14 @@ If an integer literal has no suffix, its type is the first of the following type A common use of the suffix is with calling overloaded methods. Consider, for example, the following overloaded methods that use `ulong` and [int](../../../csharp/language-reference/keywords/int.md) parameters: -```cs +```csharp public static void SampleMethod(int i) {} public static void SampleMethod(ulong l) {} ``` Using a suffix with the `ulong` parameter guarantees that the correct type is called, for example: -```cs +```csharp SampleMethod(5); // Calling the method with the int parameter SampleMethod(5UL); // Calling the method with the ulong parameter ``` @@ -86,7 +86,7 @@ SampleMethod(5UL); // Calling the method with the ulong parameter There is no implicit conversion from `ulong` to any integral type. For example, the following statement will produce a compilation error without an explicit cast: -```cs +```csharp long long1 = 8UL; // Error: no implicit conversion from ulong ``` @@ -94,7 +94,7 @@ long long1 = 8UL; // Error: no implicit conversion from ulong Also, there is no implicit conversion from floating-point types to `ulong`. For example, the following statement generates a compiler error unless an explicit cast is used: -```cs +```csharp // Error -- no implicit conversion from double: ulong x = 3.0; // OK -- explicit conversion: diff --git a/docs/csharp/language-reference/keywords/ushort.md b/docs/csharp/language-reference/keywords/ushort.md index 2667263963fb0..3e4bd9a9e0eab 100644 --- a/docs/csharp/language-reference/keywords/ushort.md +++ b/docs/csharp/language-reference/keywords/ushort.md @@ -58,14 +58,14 @@ Starting with C# 7, you can also use the underscore character, `_`, as a digit s A cast must be used when you call overloaded methods. Consider, for example, the following overloaded methods that use `ushort` and [int](../../../csharp/language-reference/keywords/int.md) parameters: -```cs +```csharp public static void SampleMethod(int i) {} public static void SampleMethod(ushort s) {} ``` Using the `ushort` cast guarantees that the correct type is called, for example: -```cs +```csharp // Calls the method with the int parameter: SampleMethod(5); // Calls the method with the ushort parameter: @@ -77,32 +77,32 @@ SampleMethod((ushort)5); There is a predefined implicit conversion from [byte](../../../csharp/language-reference/keywords/byte.md) or [char](../../../csharp/language-reference/keywords/char.md) to `ushort`. Otherwise a cast must be used to perform an explicit conversion. Consider, for example, the following two `ushort` variables `x` and `y`: -```cs +```csharp ushort x = 5, y = 12; ``` The following assignment statement will produce a compilation error, because the arithmetic expression on the right side of the assignment operator evaluates to `int` by default. -```cs +```csharp ushort z = x + y; // Error: conversion from int to ushort ``` To fix this problem, use a cast: -```cs +```csharp ushort z = (ushort)(x + y); // OK: explicit conversion ``` It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size: -```cs +```csharp int m = x + y; long n = x + y; ``` Notice also that there is no implicit conversion from floating-point types to `ushort`. For example, the following statement generates a compiler error unless an explicit cast is used: -```cs +```csharp // Error -- no implicit conversion from double: ushort x = 3.0; // OK -- explicit conversion: diff --git a/docs/csharp/language-reference/keywords/using-directive.md b/docs/csharp/language-reference/keywords/using-directive.md index b1d98787d0088..65220ed2005e6 100644 --- a/docs/csharp/language-reference/keywords/using-directive.md +++ b/docs/csharp/language-reference/keywords/using-directive.md @@ -33,13 +33,13 @@ The `using` directive has three uses: - To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace: - ```cs + ```csharp using System.Text; ``` - To allow you to access static members of a type without having to qualify the access with the type name. - ```cs + ```csharp using static System.Math; ``` @@ -47,7 +47,7 @@ The `using` directive has three uses: - To create an alias for a namespace or a type. This is called a *using alias directive*. - ```cs + ```csharp using Project = PC.MyCompany.Project; ``` @@ -56,7 +56,7 @@ The `using` directive has three uses: ## Using Static Type You can access static members of a type without having to qualify the access with the type name: -```cs +```csharp using static System.Console; using static System.Math; class Program diff --git a/docs/csharp/language-reference/keywords/using-static.md b/docs/csharp/language-reference/keywords/using-static.md index 9de26666c6a4d..2a12f9daf483d 100644 --- a/docs/csharp/language-reference/keywords/using-static.md +++ b/docs/csharp/language-reference/keywords/using-static.md @@ -31,7 +31,7 @@ translation.priority.ht: The `using static` directive designates a type whose static members you can access without specifying a type name. Its syntax is: -```cs +```csharp using static ``` diff --git a/docs/csharp/language-reference/keywords/when.md b/docs/csharp/language-reference/keywords/when.md index 9ee9d5f26e287..a06872dfec43b 100644 --- a/docs/csharp/language-reference/keywords/when.md +++ b/docs/csharp/language-reference/keywords/when.md @@ -42,7 +42,7 @@ You can use the `when` contextual keyword to specify a filter condition in two c Starting with C# 6, `When` can be used in a `catch` statement to specify a condition that must be true for the handler for a specific exception to execute. Its syntax is: -```cs +```csharp catch ExceptionType [e] when (expr) ``` where *expr* is an expression that evaluates to a Boolean value. If it returns `true`, the exception handler executes; if `false`, it does not. @@ -55,7 +55,7 @@ The following example uses the `when` keyword to conditionally execute handlers Starting with 7, `case` labels no longer need be mutually exclusive, and the order in which `case` labels appear in a `switch` statement can determine which switch block executes. The `when` keyword can be used to specify a filter condition that causes its associated case label to be true only if the filter condition is also true. Its syntax is: -```cs +```csharp case (expr) where (when-condition): ``` where *expr* is a constant pattern or type pattern that is compared to the match expression, and *when-condition* is any Boolean expression. diff --git a/docs/csharp/language-reference/keywords/where-generic-type-constraint.md b/docs/csharp/language-reference/keywords/where-generic-type-constraint.md index a9fd3fd892aed..24b046414388e 100644 --- a/docs/csharp/language-reference/keywords/where-generic-type-constraint.md +++ b/docs/csharp/language-reference/keywords/where-generic-type-constraint.md @@ -34,7 +34,7 @@ translation.priority.ht: # where (generic type constraint) (C# Reference) In a generic type definition, the `where` clause is used to specify constraints on the types that can be used as arguments for a type parameter defined in a generic declaration. For example, you can declare a generic class, `MyGenericClass`, such that the type parameter `T` implements the interface: -```cs +```csharp public class MyGenericClass where T:IComparable { } ``` @@ -57,13 +57,13 @@ public class MyGenericClass where T:IComparable { } You can also attach constraints to type parameters of generic methods, like this: -```cs +```csharp public bool MyMethod(T t) where T : IMyInterface { } ``` Notice that the syntax to describe type parameter constraints on delegates is the same as that of methods: -```cs +```csharp delegate T MyDelegate() where T : new() ``` diff --git a/docs/csharp/language-reference/keywords/yield.md b/docs/csharp/language-reference/keywords/yield.md index 867e3d8599dd2..6f02119340bc1 100644 --- a/docs/csharp/language-reference/keywords/yield.md +++ b/docs/csharp/language-reference/keywords/yield.md @@ -36,7 +36,7 @@ When you use the `yield` keyword in a statement, you indicate that the method, o The following example shows the two forms of the `yield` statement. -```cs +```csharp yield return ; yield break; ``` @@ -75,7 +75,7 @@ yield break; ## Technical Implementation The following code returns an `IEnumerable` from an iterator method and then iterates through its elements. -```cs +```csharp IEnumerable elements = MyIteratorMethod(); foreach (string element in elements) { diff --git a/docs/csharp/language-reference/operators/lambda-operator.md b/docs/csharp/language-reference/operators/lambda-operator.md index f65714c568bdd..076d0786ee491 100644 --- a/docs/csharp/language-reference/operators/lambda-operator.md +++ b/docs/csharp/language-reference/operators/lambda-operator.md @@ -38,7 +38,7 @@ The `=>` token is called the lambda operator. It is used in *lambda expressions* The following example shows two ways to find and display the length of the shortest string in an array of strings. The first part of the example applies a lambda expression (`w => w.Length`) to each element of the `words` array and then uses the method to find the smallest length. For comparison, the second part of the example shows a longer solution that uses query syntax to do the same thing. -```cs +```csharp string[] words = { "cherry", "apple", "blueberry" }; // Use method syntax to apply a lambda expression to each element @@ -64,14 +64,14 @@ Console.WriteLine(shortestWordLength2); You can specify the type of the input variable explicitly or let the compiler infer it; in either case, the variable is strongly typed at compile time. When you specify a type, you must enclose the type name and the variable name in parentheses, as the following example shows. -```cs +```csharp int shortestWordLength = words.Min((string w) => w.Length); ``` ## Example The following example shows how to write a lambda expression for the overload of the standard query operator that takes two arguments. Because the lambda expression has more than one parameter, the parameters must be enclosed in parentheses. The second parameter, `index`, represents the index of the current element in the collection. The `Where` expression returns all the strings whose lengths are less than their index positions in the array. -```cs +```csharp static void Main(string[] args) { string[] digits = { "zero", "one", "two", "three", "four", "five", diff --git a/docs/csharp/language-reference/operators/null-conditional-operators.md b/docs/csharp/language-reference/operators/null-conditional-operators.md index 8c054d4c879d3..39a85ea2bd4d3 100644 --- a/docs/csharp/language-reference/operators/null-conditional-operators.md +++ b/docs/csharp/language-reference/operators/null-conditional-operators.md @@ -29,7 +29,7 @@ translation.priority.ht: # Null-conditional Operators (C# and Visual Basic) Used to test for null before performing a member access (`?.`) or index (`?[`) operation. These operators help you write less code to handle null checks, especially for descending into data structures. -```cs +```csharp int? length = customers?.Length; // null if customers is null Customer first = customers?[0]; // null if customers is null int? count = customers?[0]?.Orders?.Count(); // null if customers, the first customer, or Orders is null @@ -53,7 +53,7 @@ A?.B?.C?[0] == E Another use for the null-condition member access is invoking delegates in a thread-safe way with much less code. The old way requires code like the following: -```cs +```csharp var handler = this.PropertyChanged; if (handler != null) handler(…) diff --git a/docs/csharp/language-reference/preprocessor-directives/preprocessor-define.md b/docs/csharp/language-reference/preprocessor-directives/preprocessor-define.md index e1d47095f73fd..3bac2de04d072 100644 --- a/docs/csharp/language-reference/preprocessor-directives/preprocessor-define.md +++ b/docs/csharp/language-reference/preprocessor-directives/preprocessor-define.md @@ -52,7 +52,7 @@ You use `#define` to define a symbol. When you use the symbol as the expression As the following example shows, you must put `#define` directives at the top of the file. -```cs +```csharp #define DEBUG //#define TRACE #undef TRACE diff --git a/docs/csharp/language-reference/tokens/verbatim.md b/docs/csharp/language-reference/tokens/verbatim.md index db1524b9f9686..b0f3f51105adb 100644 --- a/docs/csharp/language-reference/tokens/verbatim.md +++ b/docs/csharp/language-reference/tokens/verbatim.md @@ -49,7 +49,7 @@ The `@` special character serves as a verbatim identifier. It can be used in the 1. To enable the compiler to distinguish between attributes in cases of a naming conflict. An attribute is a type that derives from @System.Attribute. Its type name typically includes the suffix **Attribute**, although the compiler does not enforce this convention. The attribute can then be referenced in code either by its full type name (for example, `[InfoAttribute]` or its shortened name (for example, `[Info]`). However, a naming conflict occurs if two shortened attribute type names are identical, and one type name includes the **Attribute** suffix but the other does not. For example, the following code fails to compile because the compiler cannot determine whether the `Info` or `InfoAttribute` attribute is applied to the `Main` method. - ```cs + ```csharp using System; [AttributeUsage(AttributeTargets.Class)] diff --git a/docs/csharp/linq/dynamically-specify-predicate-filters-at-runtime.md b/docs/csharp/linq/dynamically-specify-predicate-filters-at-runtime.md index 57f6b0ff93b0f..4a0142282e838 100644 --- a/docs/csharp/linq/dynamically-specify-predicate-filters-at-runtime.md +++ b/docs/csharp/linq/dynamically-specify-predicate-filters-at-runtime.md @@ -30,7 +30,7 @@ In some cases you do not know until run time how many predicates you have to app 5. Add the following line to the `Main` method in class `DynamicPredicates`, under the declaration of `ids`. - ```cs + ```csharp QueryById(ids); ``` diff --git a/docs/csharp/linq/join-by-using-composite-keys.md b/docs/csharp/linq/join-by-using-composite-keys.md index e3431e0c0a414..251906e783922 100644 --- a/docs/csharp/linq/join-by-using-composite-keys.md +++ b/docs/csharp/linq/join-by-using-composite-keys.md @@ -19,7 +19,7 @@ This example shows how to perform join operations in which you want to use more ## Example The following example demonstrates how to use a composite key to join data from three tables: -```cs +```csharp var query = from o in db.Orders from p in db.Products join d in db.OrderDetails @@ -30,7 +30,7 @@ var query = from o in db.Orders Type inference on composite keys depends on the names of the properties in the keys, and the order in which they occur. If the properties in the source sequences do not have the same names, you must assign new names in the keys. For example, if the `Orders` table and `OrderDetails` table each used different names for their columns, you could create composite keys by assigning identical names in the anonymous types: -```cs +```csharp join...on new {Name = o.CustomerName, ID = o.CustID} equals new {Name = d.CustName, ID = d.CustID } ``` diff --git a/docs/csharp/linq/write-linq-queries.md b/docs/csharp/linq/write-linq-queries.md index 3c03e0d7834c1..d09b9ddc603a2 100644 --- a/docs/csharp/linq/write-linq-queries.md +++ b/docs/csharp/linq/write-linq-queries.md @@ -70,19 +70,19 @@ This topic shows the three ways in which you can write a LINQ query in C#: The previous query can be written by using implicit typing with `var`, as follows: -```cs +```csharp var numCount = (from num in numbers... ``` It can be written in method syntax as follows: -```cs +```csharp var numCount = numbers.Where(n => n < 3 || n > 7).Count(); ``` It can be written by using explicit typing, as follows: -```cs +```csharp int numCount = numbers.Where(n => n < 3 || n > 7).Count(); ``` diff --git a/docs/csharp/methods.md b/docs/csharp/methods.md index 3ab8b62b43336..f12d3125de504 100644 --- a/docs/csharp/methods.md +++ b/docs/csharp/methods.md @@ -192,7 +192,7 @@ Using a local variable, in this case, `result`, to store a value is optional. It Sometimes, you want your method to return more than a single value. Starting with C# 7.0, you can do this easily by using *tuple types* and *tuple literals*. The tuple type defines the data types of the tuple's elements. Tuple literals provide the actual values of the returned tuple. In teh following example, `(string, string, string, int)` defines the tuple type that is returned by the `GetPersonalInfo` method. The expression `(per.FirstName, per.MiddleName, per.LastName, per.Age)` is the tuple literal; the method returns the first, middle, and last name, along with the age, of a `PersonInfo` object. -```cs +```csharp public (string, string, string, int) GetPersonalInfo(string id) { PersonInfo per = PersonInfo.RetrieveInfoById(id); @@ -205,7 +205,7 @@ public (string, string, string, int) GetPersonalInfo(string id) The caller can then consume the returned tuple with code like the following: -```cs +```csharp var person = GetPersonalInfo("111111111") if (person != null) Console.WriteLine("{person.Item1} {person.Item3}: age = {person.Item4}"); @@ -213,7 +213,7 @@ if (person != null) Names can also be assigned to the tuple elements in the tuple type definition. The following example shows an alternate version of the `GetPersonalInfo` method that uses named elements: -```cs +```csharp public (string FName, string MName, string LName, int Age) GetPersonalInfo(string id) { PersonInfo per = PersonInfo.RetrieveInfoById(id); @@ -226,7 +226,7 @@ public (string FName, string MName, string LName, int Age) GetPersonalInfo(strin The previous call to the `GetPersonInfo` method can then be modified as follows: -```cs +```csharp var person = GetPersonalInfo("111111111"); if (person != null) Console.WriteLine("{person.FName} {person.LName}: age = {person.Age}"); @@ -273,7 +273,7 @@ An async method can't declare any [ref](https://msdn.microsoft.com/library/14akc It is common to have method definitions that simply return immediately with the result of an expression, or that have a single statement as the body of the method. There is a syntax shortcut for defining such methods using `=>`: -```cs +```csharp public Point Move(int dx, int dy) => new Point(x + dx, y + dy); public void Print() => Console.WriteLine(First + " " + Last); diff --git a/docs/csharp/misc/cs0168.md b/docs/csharp/misc/cs0168.md index 555ebc4477042..9be6e5884e8ac 100644 --- a/docs/csharp/misc/cs0168.md +++ b/docs/csharp/misc/cs0168.md @@ -37,7 +37,7 @@ The compiler issues a level-three warning when you declare a variable, but do no The following sample generates a CS0168 warning: -```cs +```csharp // CS0168.cs // compile with: /W:3 public class clx diff --git a/docs/csharp/misc/cs0415.md b/docs/csharp/misc/cs0415.md index d4d659ba9f1aa..064d0eb87b1e5 100644 --- a/docs/csharp/misc/cs0415.md +++ b/docs/csharp/misc/cs0415.md @@ -43,7 +43,7 @@ The 'IndexerName' attribute is valid only on an indexer that is not an explicit The following sample generates CS0415: -```cs +```csharp // CS0415.cs using System; using System.Runtime.CompilerServices; diff --git a/docs/csharp/misc/cs0428.md b/docs/csharp/misc/cs0428.md index 10f1871afe796..d42a2b3ec18a7 100644 --- a/docs/csharp/misc/cs0428.md +++ b/docs/csharp/misc/cs0428.md @@ -44,7 +44,7 @@ Cannot convert method group 'Identifier' to non-delegate type 'type'. Did you ## Example The following sample generates CS0428: -```cs +```csharp // CS0428.cs namespace ConsoleApplication1 { diff --git a/docs/csharp/misc/cs0542.md b/docs/csharp/misc/cs0542.md index ddd524215204e..9d64aa0c3864d 100644 --- a/docs/csharp/misc/cs0542.md +++ b/docs/csharp/misc/cs0542.md @@ -43,7 +43,7 @@ translation.priority.mt: The following sample generates CS0542: -```cs +```csharp // CS0542.cs class C { @@ -53,7 +53,7 @@ class C This error might be caused if you inadvertently put a return type on a constructor, which in effect makes it into an ordinary method. The following example generates CS0542 because `F` is a method, not a constructor, because it has a return type: -```cs +```csharp // CS0542.cs class F { @@ -73,7 +73,7 @@ class MyClass If your class is named 'Item' and has an indexer declared as `this`, you may get this error. A default indexer is given the name 'Item' in the emitted code, creating the conflict. -```cs +```csharp // CS0542b.cs class Item { diff --git a/docs/csharp/misc/cs0625.md b/docs/csharp/misc/cs0625.md index 4db51fecf0730..25785a8d50785 100644 --- a/docs/csharp/misc/cs0625.md +++ b/docs/csharp/misc/cs0625.md @@ -43,7 +43,7 @@ When a struct is marked with an explicit **StructLayout** attribute, all fields The following sample generates CS0625: -```cs +```csharp // CS0625.cs // compile with: /target:library using System; diff --git a/docs/csharp/misc/cs0626.md b/docs/csharp/misc/cs0626.md index c88d22943806d..f8190d3b87426 100644 --- a/docs/csharp/misc/cs0626.md +++ b/docs/csharp/misc/cs0626.md @@ -45,7 +45,7 @@ Method, operator, or accessor 'method' is marked external and has no attributes The following sample generates CS0626: -```cs +```csharp // CS0626.cs // compile with: /warnaserror using System.Runtime.InteropServices; diff --git a/docs/csharp/misc/cs0662.md b/docs/csharp/misc/cs0662.md index 95719ef955717..e945b69c78e0a 100644 --- a/docs/csharp/misc/cs0662.md +++ b/docs/csharp/misc/cs0662.md @@ -43,7 +43,7 @@ translation.priority.mt: The following sample generates CS0662: -```cs +```csharp // CS0662.cs using System.Runtime.InteropServices; diff --git a/docs/csharp/misc/cs0664.md b/docs/csharp/misc/cs0664.md index 6456ce77c6f62..8922b5cced9c1 100644 --- a/docs/csharp/misc/cs0664.md +++ b/docs/csharp/misc/cs0664.md @@ -43,7 +43,7 @@ Literal of type double cannot be implicitly converted to type 'type'; use an 'su The following sample generates CS0664: -```cs +```csharp // CS0664.cs class Example { diff --git a/docs/csharp/misc/cs0668.md b/docs/csharp/misc/cs0668.md index 74f3f862e034a..1a434d74e547b 100644 --- a/docs/csharp/misc/cs0668.md +++ b/docs/csharp/misc/cs0668.md @@ -43,7 +43,7 @@ Two indexers have different names; the IndexerName attribute must be used with t The following sample generates CS0668: -```cs +```csharp // CS0668.cs using System; using System.Runtime.CompilerServices; diff --git a/docs/csharp/misc/cs0669.md b/docs/csharp/misc/cs0669.md index 4f38a306f5534..597afe8ea4c27 100644 --- a/docs/csharp/misc/cs0669.md +++ b/docs/csharp/misc/cs0669.md @@ -43,7 +43,7 @@ A class with the ComImport attribute cannot have a user-defined constructor. The following sample generates CS0669: -```cs +```csharp // CS0669.cs using System.Runtime.InteropServices; [ComImport, Guid("00000000-0000-0000-0000-000000000001")] diff --git a/docs/csharp/misc/cs1944.md b/docs/csharp/misc/cs1944.md index e78ab395f4f57..749adade180b6 100644 --- a/docs/csharp/misc/cs1944.md +++ b/docs/csharp/misc/cs1944.md @@ -48,7 +48,7 @@ An expression tree may not contain an unsafe pointer operation ## Example The following example generates CS1944: -```cs +```csharp // cs1944.cs // Compile with: /unsafe using System.Linq.Expressions; diff --git a/docs/csharp/modern-events.md b/docs/csharp/modern-events.md index 92480a3c1eb6f..cdca8855a3b25 100644 --- a/docs/csharp/modern-events.md +++ b/docs/csharp/modern-events.md @@ -36,7 +36,7 @@ The program will work exactly the same. You could also change the `SearchDirectoryArgs` to a struct, if you also make one more change: -```cs +```csharp internal struct SearchDirectoryArgs { internal string CurrentSearchDirectory { get; } @@ -92,7 +92,7 @@ You need to reconcile this opposing guidance. Somehow, you must create a safe `async void` method. The basics of the pattern you need to implement are below: -```cs +```csharp worker.StartWorking += async (sender, eventArgs) => { try diff --git a/docs/csharp/programming-guide/classes-and-structs/anonymous-types.md b/docs/csharp/programming-guide/classes-and-structs/anonymous-types.md index 8a9918e80e603..3bbaa0f2cb4e1 100644 --- a/docs/csharp/programming-guide/classes-and-structs/anonymous-types.md +++ b/docs/csharp/programming-guide/classes-and-structs/anonymous-types.md @@ -41,7 +41,7 @@ Anonymous types provide a convenient way to encapsulate a set of read-only prope The following example shows an anonymous type that is initialized with two properties named `Amount` and `Message`. -```cs +```csharp var v = new { Amount = 108, Message = "Hello" }; @@ -65,7 +65,7 @@ Console.WriteLine(v.Amount + v.Message); You can create an array of anonymously typed elements by combining an implicitly typed local variable and an implicitly typed array, as shown in the following example. -```cs +```csharp var anonArray = new[] { new { name = "apple", diam = 4 }, new { name = "grape", diam = 1 }}; ``` diff --git a/docs/csharp/programming-guide/classes-and-structs/auto-implemented-properties.md b/docs/csharp/programming-guide/classes-and-structs/auto-implemented-properties.md index 35faac02c655e..8b34d354653f8 100644 --- a/docs/csharp/programming-guide/classes-and-structs/auto-implemented-properties.md +++ b/docs/csharp/programming-guide/classes-and-structs/auto-implemented-properties.md @@ -44,7 +44,7 @@ In C# 3.0 and later, auto-implemented properties make property-declaration more In C# 6 and later, you can initialize auto-implemented properties similarly to fields: -```cs +```csharp public string FirstName { get; set; } = "Jane"; ``` diff --git a/docs/csharp/programming-guide/classes-and-structs/how-to-access-a-collection-class-with-foreach.md b/docs/csharp/programming-guide/classes-and-structs/how-to-access-a-collection-class-with-foreach.md index 3776536625f72..24348a18014d5 100644 --- a/docs/csharp/programming-guide/classes-and-structs/how-to-access-a-collection-class-with-foreach.md +++ b/docs/csharp/programming-guide/classes-and-structs/how-to-access-a-collection-class-with-foreach.md @@ -52,7 +52,7 @@ The following code example illustrates how to write a non-generic collection cla For example, change the following lines in the previous example. -```cs +```csharp // Change the Tokens class so that it no longer implements IEnumerable. public class Tokens @@ -78,7 +78,7 @@ public class Tokens Because `Current` returns a string, the compiler can detect when an incompatible type is used in a `foreach` statement, as shown in the following code. -```cs +```csharp // Error: Cannot convert type string to int. foreach (int item in f) diff --git a/docs/csharp/programming-guide/classes-and-structs/how-to-implement-a-lightweight-class-with-auto-implemented-properties.md b/docs/csharp/programming-guide/classes-and-structs/how-to-implement-a-lightweight-class-with-auto-implemented-properties.md index 9c2f34673da18..c181dddf2c989 100644 --- a/docs/csharp/programming-guide/classes-and-structs/how-to-implement-a-lightweight-class-with-auto-implemented-properties.md +++ b/docs/csharp/programming-guide/classes-and-structs/how-to-implement-a-lightweight-class-with-auto-implemented-properties.md @@ -44,7 +44,7 @@ This example shows how to create an immutable lightweight class that serves only ## Example The following example shows two ways to implement an immutable class that has auto-implemented properties. Each way declares one of the properties with a private `set` and one of the properties with a `get` only. The first class uses a constructor only to initialize the properties, and the second class uses a static factory method that calls a constructor. -```cs +```csharp // This class is immutable. After an object is created,  // it cannot be modified from outside the class. It uses a  // constructor to initialize its properties.  diff --git a/docs/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method.md b/docs/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method.md index 49abc29a7d23b..6eb20dcfd2c4d 100644 --- a/docs/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method.md +++ b/docs/csharp/programming-guide/classes-and-structs/how-to-override-the-tostring-method.md @@ -50,7 +50,7 @@ Every class or struct in C# implicitly inherits the class. 1. Declare a `ToString` method with the following modifiers and return type: - ```cs + ```csharp public override string ToString(){} ``` diff --git a/docs/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords.md b/docs/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords.md index 3fd1d6ed8763d..3873d2fa0643c 100644 --- a/docs/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords.md +++ b/docs/csharp/programming-guide/classes-and-structs/knowing-when-to-use-override-and-new-keywords.md @@ -40,7 +40,7 @@ In C#, a method in a derived class can have the same name as a method in the bas In a console application, declare the following two classes, `BaseClass` and `DerivedClass`. `DerivedClass` inherits from `BaseClass`. -```cs +```csharp class BaseClass { public void Method1() @@ -69,7 +69,7 @@ class DerivedClass : BaseClass Because `bc` and `bcdc` have type `BaseClass`, they can only directly access `Method1`, unless you use casting. Variable `dc` can access both `Method1` and `Method2`. These relationships are shown in the following code. -```cs +```csharp class Program { static void Main(string[] args) @@ -94,7 +94,7 @@ class Program Next, add the following `Method2` method to `BaseClass`. The signature of this method matches the signature of the `Method2` method in `DerivedClass`. -```cs +```csharp public void Method2() { Console.WriteLine("Base - Method2"); @@ -104,7 +104,7 @@ public void Method2() Because `BaseClass` now has a `Method2` method, a second calling statement can be added for `BaseClass` variables `bc` and `bcdc`, as shown in the following code. -```cs +```csharp bc.Method1(); bc.Method2(); dc.Method1(); @@ -118,7 +118,7 @@ bcdc.Method2(); Before adding `new`, run the program to see the output produced by the additional calling statements. The following results are displayed. -```cs +```csharp // Output: // Base - Method1 // Base - Method2 @@ -133,7 +133,7 @@ bcdc.Method2(); To suppress the warning, add the `new` modifier to the definition of `Method2` in `DerivedClass`, as shown in the following code. The modifier can be added before or after `public`. -```cs +```csharp public new void Method2() { Console.WriteLine("Derived - Method2"); @@ -145,7 +145,7 @@ public new void Method2() To contrast this behavior to the effects of using `override`, add the following method to `DerivedClass`. The `override` modifier can be added before or after `public`. -```cs +```csharp public override void Method1() { Console.WriteLine("Derived - Method1"); @@ -155,7 +155,7 @@ public override void Method1() Add the `virtual` modifier to the definition of `Method1` in `BaseClass`. The `virtual` modifier can be added before or after `public`. -```cs +```csharp public virtual void Method1() { Console.WriteLine("Base - Method1"); @@ -165,7 +165,7 @@ public virtual void Method1() Run the project again. Notice especially the last two lines of the following output. -```cs +```csharp // Output: // Base - Method1 // Base - Method2 @@ -180,7 +180,7 @@ public virtual void Method1() The following code contains the full example. -```cs +```csharp using System; using System.Text; @@ -251,7 +251,7 @@ namespace OverrideAndNew The following example illustrates similar behavior in a different context. The example defines three classes: a base class named `Car` and two classes that are derived from it, `ConvertibleCar` and `Minivan`. The base class contains a `DescribeCar` method. The method displays a basic description of a car, and then calls `ShowDetails` to provide additional information. Each of the three classes defines a `ShowDetails` method. The `new` modifier is used to define `ShowDetails` in the `ConvertibleCar` class. The `override` modifier is used to define `ShowDetails` in the `Minivan` class. -```cs +```csharp // Define the base class, Car. The class defines two methods, // DescribeCar and ShowDetails. DescribeCar calls ShowDetails, and each derived // class also defines a ShowDetails method. The example tests which version of @@ -296,7 +296,7 @@ class Minivan : Car The example tests which version of `ShowDetails` is called. The following method, `TestCars1`, declares an instance of each class, and then calls `DescribeCar` on each instance. -```cs +```csharp public static void TestCars1() { System.Console.WriteLine("\nTestCars1"); @@ -323,7 +323,7 @@ public static void TestCars1() `TestCars1` produces the following output. Notice especially the results for `car2`, which probably are not what you expected. The type of the object is `ConvertibleCar`, but `DescribeCar` does not access the version of `ShowDetails` that is defined in the `ConvertibleCar` class because that method is declared with the `new` modifier, not the `override` modifier. As a result, a `ConvertibleCar` object displays the same description as a `Car` object. Contrast the results for `car3`, which is a `Minivan` object. In this case, the `ShowDetails` method that is declared in the `Minivan` class overrides the `ShowDetails` method that is declared in the `Car` class, and the description that is displayed describes a minivan. -```cs +```csharp // TestCars1 // ---------- @@ -341,7 +341,7 @@ public static void TestCars1() `TestCars2` creates a list of objects that have type `Car`. The values of the objects are instantiated from the `Car`, `ConvertibleCar`, and `Minivan` classes. `DescribeCar` is called on each element of the list. The following code shows the definition of `TestCars2`. -```cs +```csharp public static void TestCars2() { System.Console.WriteLine("\nTestCars2"); @@ -361,7 +361,7 @@ public static void TestCars2() The following output is displayed. Notice that it is the same as the output that is displayed by `TestCars1`. The `ShowDetails` method of the `ConvertibleCar` class is not called, regardless of whether the type of the object is `ConvertibleCar`, as in `TestCars1`, or `Car`, as in `TestCars2`. Conversely, `car3` calls the `ShowDetails` method from the `Minivan` class in both cases, whether it has type `Minivan` or type `Car`. -```cs +```csharp // TestCars2 // ---------- // Four wheels and an engine. @@ -378,7 +378,7 @@ public static void TestCars2() Methods `TestCars3` and `TestCars4` complete the example. These methods call `ShowDetails` directly, first from objects declared to have type `ConvertibleCar` and `Minivan` (`TestCars3`), then from objects declared to have type `Car` (`TestCars4`). The following code defines these two methods. -```cs +```csharp public static void TestCars3() { @@ -404,7 +404,7 @@ public static void TestCars4() The methods produce the following output, which corresponds to the results from the first example in this topic. -```cs +```csharp // TestCars3 // ---------- // A roof that opens up. @@ -419,7 +419,7 @@ public static void TestCars4() The following code shows the complete project and its output. -```cs +```csharp using System; using System.Collections.Generic; using System.Linq; diff --git a/docs/csharp/programming-guide/classes-and-structs/methods.md b/docs/csharp/programming-guide/classes-and-structs/methods.md index 8e361d8cb9269..6d12f3941e72e 100644 --- a/docs/csharp/programming-guide/classes-and-structs/methods.md +++ b/docs/csharp/programming-guide/classes-and-structs/methods.md @@ -93,7 +93,7 @@ A method is a code block that contains a series of statements. A program causes Returning a multi-dimensional array from a method, M, that modifies the array's contents is not necessary if the calling function passed the array into M. You may return the resulting array from M for good style or functional flow of values, but it is not necessary. The reason you do not need to return the modified array is that C# passes all reference types by value, and the value of an array reference is the pointer to the array. In the method M, any changes to the array's contents are observable by any code that has a reference to the array, as shown in the following example. -```cs +```csharp static void Main(string[] args) { int[,] matrix = new int[2, 2]; @@ -139,7 +139,7 @@ static void Main(string[] args) ## Expression Body Definitions It is common to have method definitions that simply return immediately with the result of an expression, or that have a single statement as the body of the method. There is a syntax shortcut for defining such methods using `=>`: -```cs +```csharp public Point Move(int dx, int dy) => new Point(x + dx, y + dy); public void Print() => Console.WriteLine(First + " " + Last); // Works with operators, properties, and indexers too. diff --git a/docs/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members.md b/docs/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members.md index 284dd233067b1..6fe489dbe9f91 100644 --- a/docs/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members.md +++ b/docs/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members.md @@ -40,7 +40,7 @@ translation.priority.ht: # Static Classes and Static Class Members (C# Programming Guide) A [static](../../../csharp/language-reference/keywords/static.md) class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the [new](../../../csharp/language-reference/keywords/new.md) keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself. For example, if you have a static class that is named `UtilityClass` that has a public method named `MethodA`, you call the method as shown in the following example: -```cs +```csharp UtilityClass.MethodA(); ``` diff --git a/docs/csharp/programming-guide/concepts/assemblies-gac/friend-assemblies.md b/docs/csharp/programming-guide/concepts/assemblies-gac/friend-assemblies.md index 7f5137e0fdec0..42228de7930e5 100644 --- a/docs/csharp/programming-guide/concepts/assemblies-gac/friend-assemblies.md +++ b/docs/csharp/programming-guide/concepts/assemblies-gac/friend-assemblies.md @@ -35,7 +35,7 @@ A *friend assembly* is an assembly that can access another assembly's [internal] > [!NOTE] > When you compile an assembly (assembly `AssemblyB`) that will access internal types or internal members of another assembly (assembly *A*), you must explicitly specify the name of the output file (.exe or .dll) by using the **/out** compiler option. This is required because the compiler has not yet generated the name for the assembly it is building at the time it is binding to external references. For more information, see [/out (C#)](../../../../csharp/language-reference/compiler-options/out-compiler-option.md) . -```cs +```csharp using System.Runtime.CompilerServices; using System; diff --git a/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-and-use-assemblies-using-the-command-line.md b/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-and-use-assemblies-using-the-command-line.md index 05c2dc6723524..b5d40f14c049e 100644 --- a/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-and-use-assemblies-using-the-command-line.md +++ b/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-and-use-assemblies-using-the-command-line.md @@ -35,7 +35,7 @@ An assembly, or a dynamic linking library (DLL), is linked to your program at ru ## Example -```cs +```csharp // File: Add.cs namespace UtilityMethods { @@ -49,7 +49,7 @@ namespace UtilityMethods } ``` -```cs +```csharp // File: Mult.cs namespace UtilityMethods { @@ -63,7 +63,7 @@ namespace UtilityMethods } ``` -```cs +```csharp // File: TestCode.cs using UtilityMethods; @@ -101,13 +101,13 @@ class TestCode Notice that the `using` directive at the beginning of the file enables you to use the unqualified class names to reference the DLL methods at compile time, as follows: -```cs +```csharp MultiplyClass.Multiply(num1, num2); ``` Otherwise, you have to use the fully qualified names, as follows: -```cs +```csharp UtilityMethods.MultiplyClass.Multiply(num1, num2); ``` @@ -119,7 +119,7 @@ UtilityMethods.MultiplyClass.Multiply(num1, num2); ## Compiling the Code To build the file `MathLibrary.DLL`, compile the two files `Add` and `Mult` by using the following command line. -```cs +```csharp csc /target:library /out:MathLibrary.DLL Add.cs Mult.cs ``` @@ -127,7 +127,7 @@ csc /target:library /out:MathLibrary.DLL Add.cs Mult.cs To build the executable file, `TestCode.exe`, use the following command line: -```cs +```csharp csc /out:TestCode.exe /reference:MathLibrary.DLL TestCode.cs ``` diff --git a/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-signed-friend-assemblies.md b/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-signed-friend-assemblies.md index 0f2ad0125e40e..a9d3b5f0fd9ad 100644 --- a/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-signed-friend-assemblies.md +++ b/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-signed-friend-assemblies.md @@ -47,7 +47,7 @@ This example shows how to use friend assemblies with assemblies that have strong The Strong Name tool generates a new public key every time it runs. Therefore, you must replace the public key in the following code with the public key you just generated, as shown in the following example. - ```cs + ```csharp // friend_signed_A.cs // Compile with: // csc /target:library /keyfile:FriendAssemblies.snk friend_signed_A.cs @@ -66,13 +66,13 @@ This example shows how to use friend assemblies with assemblies that have strong 4. Compile and sign friend_signed_A by using the following command. - ```cs + ```csharp csc /target:library /keyfile:FriendAssemblies.snk friend_signed_A.cs ``` 5. Create a C# file that is named `friend_signed_B` and contains the following code. Because friend_signed_A specifies friend_signed_B as a friend assembly, the code in friend_signed_B can access `internal` types and members from friend_signed_A. The file contains the following code. - ```cs + ```csharp // friend_signed_B.cs // Compile with: // csc /keyfile:FriendAssemblies.snk /r:friend_signed_A.dll /out:friend_signed_B.exe friend_signed_B.cs @@ -88,7 +88,7 @@ This example shows how to use friend assemblies with assemblies that have strong 6. Compile and sign friend_signed_B by using the following command. - ```cs + ```csharp csc /keyfile:FriendAssemblies.snk /r:friend_signed_A.dll /out:friend_signed_B.exe friend_signed_B.cs ``` diff --git a/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-unsigned-friend-assemblies.md b/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-unsigned-friend-assemblies.md index 3279713162da0..8db7fabb3a3a6 100644 --- a/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-unsigned-friend-assemblies.md +++ b/docs/csharp/programming-guide/concepts/assemblies-gac/how-to-create-unsigned-friend-assemblies.md @@ -31,7 +31,7 @@ This example shows how to use friend assemblies with assemblies that are unsigne 2. Create a C# file named `friend_signed_A.` that contains the following code. The code uses the attribute to declare friend_signed_B as a friend assembly. - ```cs + ```csharp // friend_unsigned_A.cs // Compile with: // csc /target:library friend_unsigned_A.cs @@ -61,13 +61,13 @@ This example shows how to use friend assemblies with assemblies that are unsigne 3. Compile and sign friend_signed_A by using the following command. - ```cs + ```csharp csc /target:library friend_unsigned_A.cs ``` 4. Create a C# file named `friend_unsigned_B` that contains the following code. Because friend_unsigned_A specifies friend_unsigned_B as a friend assembly, the code in friend_unsigned_B can access `internal` types and members from friend_unsigned_A. - ```cs + ```csharp // friend_unsigned_B.cs // Compile with: // csc /r:friend_unsigned_A.dll /out:friend_unsigned_B.exe friend_unsigned_B.cs @@ -90,7 +90,7 @@ This example shows how to use friend assemblies with assemblies that are unsigne 5. Compile friend_signed_B by using the following command. - ```cs + ```csharp csc /r:friend_unsigned_A.dll /out:friend_unsigned_B.exe friend_unsigned_B.cs ``` diff --git a/docs/csharp/programming-guide/concepts/assemblies-gac/walkthrough-embedding-type-information-from-microsoft-office-assemblies.md b/docs/csharp/programming-guide/concepts/assemblies-gac/walkthrough-embedding-type-information-from-microsoft-office-assemblies.md index 0996c575e9557..65d89f8df779d 100644 --- a/docs/csharp/programming-guide/concepts/assemblies-gac/walkthrough-embedding-type-information-from-microsoft-office-assemblies.md +++ b/docs/csharp/programming-guide/concepts/assemblies-gac/walkthrough-embedding-type-information-from-microsoft-office-assemblies.md @@ -53,7 +53,7 @@ If you embed type information in an application that references COM objects, you 7. Open the **Program.cs** file. Replace the code in the file with the following code: - ```cs + ```csharp using System; using System.Collections.Generic; using System.Linq; diff --git a/docs/csharp/programming-guide/concepts/assemblies-gac/walkthrough-embedding-types-from-managed-assemblies-in-visual-studio.md b/docs/csharp/programming-guide/concepts/assemblies-gac/walkthrough-embedding-types-from-managed-assemblies-in-visual-studio.md index a2fd239aa616c..34f6bfa0d959c 100644 --- a/docs/csharp/programming-guide/concepts/assemblies-gac/walkthrough-embedding-types-from-managed-assemblies-in-visual-studio.md +++ b/docs/csharp/programming-guide/concepts/assemblies-gac/walkthrough-embedding-types-from-managed-assemblies-in-visual-studio.md @@ -77,7 +77,7 @@ If you embed type information from a strong-named managed assembly, you can loos 6. Open the ISampleInterface.cs file. Add the following code to the ISampleInterface class file to create the ISampleInterface interface. - ```cs + ```csharp using System; using System.Runtime.InteropServices; @@ -99,7 +99,7 @@ If you embed type information from a strong-named managed assembly, you can loos 9. In **Solution Explorer**, expand the **Properties** folder. Double-click the AssemblyInfo.cs file. Add the following attribute to the file. - ```cs + ```csharp [assembly: ImportedFromTypeLib("")] ``` @@ -129,7 +129,7 @@ If you embed type information from a strong-named managed assembly, you can loos 8. Add the following code to the SampleClass class file to create the SampleClass class. - ```cs + ```csharp using System; using System.Collections.Generic; using System.Linq; @@ -172,7 +172,7 @@ If you embed type information from a strong-named managed assembly, you can loos 6. Add the following code to the Program.cs file to create the client program. - ```cs + ```csharp using System; using System.Collections.Generic; using System.Linq; @@ -210,7 +210,7 @@ If you embed type information from a strong-named managed assembly, you can loos 3. Open the SampleInterface.cs file. Add the following line of code to the ISampleInterface interface. - ```cs + ```csharp DateTime GetDate(); ``` @@ -230,7 +230,7 @@ If you embed type information from a strong-named managed assembly, you can loos 3. Open the SampleClass.cs file. Add the following lines of code to the SampleClass class. - ```cs + ```csharp public DateTime GetDate() { return DateTime.Now; diff --git a/docs/csharp/programming-guide/concepts/async/async-return-types.md b/docs/csharp/programming-guide/concepts/async/async-return-types.md index b0b745597995e..b9e3720822c3d 100644 --- a/docs/csharp/programming-guide/concepts/async/async-return-types.md +++ b/docs/csharp/programming-guide/concepts/async/async-return-types.md @@ -35,7 +35,7 @@ Async methods have three possible return types: `. -```cs +```csharp // TASK EXAMPLE async Task TaskOfT_MethodAsync() { @@ -61,7 +61,7 @@ async Task TaskOfT_MethodAsync() The following code calls and awaits method `TaskOfT_MethodAsync`. The result is assigned to the `result1` variable. -```cs +```csharp // Call and await the Task-returning async method in the same statement. int result1 = await TaskOfT_MethodAsync(); ``` @@ -71,7 +71,7 @@ int result1 = await TaskOfT_MethodAsync(); > [!WARNING] > The property is a blocking property. If you try to access it before its task is finished, the thread that's currently active is blocked until the task completes and the value is available. In most cases, you should access the value by using `await` instead of accessing the property directly. -```cs +```csharp // Call and await in separate statements. Task integerTask = TaskOfT_MethodAsync(); @@ -83,7 +83,7 @@ int result2 = await integerTask; The display statements in the following code verify that the values of the `result1` variable, the `result2` variable, and the `Result` property are the same. Remember that the `Result` property is a blocking property and shouldn't be accessed before its task has been awaited. -```cs +```csharp // Display the values of the result1 variable, the result2 variable, and // the integerTask.Result property. textBox1.Text += String.Format("\r\nValue of result1 variable: {0}\r\n", result1); @@ -96,7 +96,7 @@ textBox1.Text += String.Format("Value of integerTask.Result: {0}\r\n", integerTa In the following example, async method `Task_MethodAsync` doesn't contain a return statement. Therefore, you specify a return type of `Task` for the method, which enables `Task_MethodAsync` to be awaited. The definition of the `Task` type doesn't include a `Result` property to store a return value. -```cs +```csharp // TASK EXAMPLE async Task Task_MethodAsync() { @@ -115,7 +115,7 @@ async Task Task_MethodAsync() The following code calls and awaits method `Task_MethodAsync`. -```cs +```csharp // Call and await the Task-returning async method in the same statement. await Task_MethodAsync(); ``` @@ -124,7 +124,7 @@ await Task_MethodAsync(); The following code separates calling `Task_MethodAsync` from awaiting the task that `Task_MethodAsync` returns. -```cs +```csharp // Call and await in separate statements. Task simpleTask = Task_MethodAsync(); @@ -143,7 +143,7 @@ await simpleTask; The following code defines an async event handler. -```cs +```csharp // VOID EXAMPLE private async void button1_Click(object sender, RoutedEventArgs e) { @@ -181,7 +181,7 @@ private async void button1_Click(object sender, RoutedEventArgs e) 6. In the **XAML** window of MainWindow.xaml, replace the code with the following code. - ```cs + ```csharp method to notify `cts` when the user requests cancellation. - ```cs + ```csharp // ***Add an event handler for the Cancel button. private void cancelButton_Click(object sender, RoutedEventArgs e) { @@ -83,14 +83,14 @@ You can set up a button that you can use to cancel an async application if you d - Instantiate the `CancellationTokenSource`, `cts`. - ```cs + ```csharp // ***Instantiate the CancellationTokenSource. cts = new CancellationTokenSource(); ``` - In the call to `AccessTheWebAsync`, which downloads the contents of a specified website, send the property of `cts` as an argument. The `Token` property propagates the message if cancellation is requested. Add a catch block that displays a message if the user chooses to cancel the download operation. The following code shows the changes. - ```cs + ```csharp try { // ***Send a token to carry the message if cancellation is requested. @@ -113,7 +113,7 @@ You can set up a button that you can use to cancel an async application if you d The following code shows the changes in `AccessTheWebAsync`. - ```cs + ```csharp // ***Provide a parameter for the CancellationToken. async Task AccessTheWebAsync(CancellationToken ct) { @@ -176,7 +176,7 @@ You can set up a button that you can use to cancel an async application if you d 1. Add a method to create a list of web addresses. - ```cs + ```csharp // ***Add a method that creates a list of web addresses. private List SetUpURLList() { @@ -196,14 +196,14 @@ You can set up a button that you can use to cancel an async application if you d 2. Call the method in `AccessTheWebAsync`. - ```cs + ```csharp // ***Call SetUpURLList to make a list of web addresses. List urlList = SetUpURLList(); ``` 3. Add the following loop in `AccessTheWebAsync` to process each web address in the list. - ```cs + ```csharp // ***Add a loop to process the list of web addresses. foreach (var url in urlList) { @@ -222,13 +222,13 @@ You can set up a button that you can use to cancel an async application if you d 4. Because `AccessTheWebAsync` displays the lengths, the method doesn't need to return anything. Remove the return statement, and change the return type of the method to instead of . - ```cs + ```csharp async Task AccessTheWebAsync(CancellationToken ct) ``` Call the method from `startButton_Click` by using a statement instead of an expression. - ```cs + ```csharp await AccessTheWebAsync(cts.Token); ``` @@ -275,7 +275,7 @@ You can set up a button that you can use to cancel an async application if you d ### Cancel a Task Example The following code is the complete MainWindow.xaml.cs file for the example that cancels a single task. -```cs +```csharp using System; using System.Collections.Generic; using System.Linq; @@ -386,7 +386,7 @@ namespace CancelATask ### Cancel a List of Tasks Example The following code is the complete MainWindow.xaml.cs file for the example that cancels a list of tasks. -```cs +```csharp using System; using System.Collections.Generic; using System.Linq; diff --git a/docs/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time.md b/docs/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time.md index 1cae4a83569f5..f06109e83db7e 100644 --- a/docs/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time.md +++ b/docs/csharp/programming-guide/concepts/async/cancel-async-tasks-after-a-period-of-time.md @@ -56,7 +56,7 @@ You can cancel an asynchronous operation after a period of time by using the ProcessURLAsync(string url, HttpClient client, CancellationToken ct) { @@ -78,7 +78,7 @@ async Task ProcessURLAsync(string url, HttpClient client, CancellationToken 2. Create a query that, when executed, produces a collection of generic tasks. Each call to `ProcessURLAsync` returns a where `TResult` is an integer. - ```cs + ```csharp // ***Create a query that, when executed, returns a collection of tasks. IEnumerable> downloadTasksQuery = from url in urlList select ProcessURLAsync(url, client, ct); @@ -86,14 +86,14 @@ async Task ProcessURLAsync(string url, HttpClient client, CancellationToken 3. Call `ToArray` to execute the query and start the tasks. The application of the `WhenAny` method in the next step would execute the query and start the tasks without using `ToArray`, but other methods might not. The safest practice is to force execution of the query explicitly. - ```cs + ```csharp // ***Use ToArray to execute the query and start the download tasks. Task[] downloadTasks = downloadTasksQuery.ToArray(); ``` 4. Call `WhenAny` on the collection of tasks. `WhenAny` returns a `Task(Of Task(Of Integer))` or `Task>`. That is, `WhenAny` returns a task that evaluates to a single `Task(Of Integer)` or `Task` when it’s awaited. That single task is the first task in the collection to finish. The task that finished first is assigned to `firstFinishedTask`. The type of `firstFinishedTask` is where `TResult` is an integer because that's the return type of `ProcessURLAsync`. - ```cs + ```csharp // ***Call WhenAny and then await the result. The task that finishes // first is assigned to firstFinishedTask. Task firstFinishedTask = await Task.WhenAny(downloadTasks); @@ -101,14 +101,14 @@ async Task ProcessURLAsync(string url, HttpClient client, CancellationToken 5. In this example, you’re interested only in the task that finishes first. Therefore, use to cancel the remaining tasks. - ```cs + ```csharp // ***Cancel the rest of the downloads. You just want the first one. cts.Cancel(); ``` 6. Finally, await `firstFinishedTask` to retrieve the length of the downloaded content. - ```cs + ```csharp var length = await firstFinishedTask; resultsTextBox.Text += String.Format("\r\nLength of the downloaded website: {0}\r\n", length); ``` @@ -122,7 +122,7 @@ async Task ProcessURLAsync(string url, HttpClient client, CancellationToken You can download the project from [Async Sample: Fine Tuning Your Application](http://go.microsoft.com/fwlink/?LinkId=255046). -```cs +```csharp using System; using System.Collections.Generic; using System.Linq; diff --git a/docs/csharp/programming-guide/concepts/async/control-flow-in-async-programs.md b/docs/csharp/programming-guide/concepts/async/control-flow-in-async-programs.md index 3fecbff9414b7..669b87fef94a9 100644 --- a/docs/csharp/programming-guide/concepts/async/control-flow-in-async-programs.md +++ b/docs/csharp/programming-guide/concepts/async/control-flow-in-async-programs.md @@ -40,7 +40,7 @@ You can write and maintain asynchronous programs more easily by using the `async The following code shows an outline of the program. -```cs +```csharp public partial class MainWindow : Window { @@ -144,7 +144,7 @@ Length of the downloaded string: 33946. 6. In the **XAML** view of MainWindow.xaml, replace the code with the following code. - ```cs + ```csharp getStringTask = client.GetStringAsync("http://msdn.microsoft.com"); ``` @@ -316,7 +316,7 @@ THREE: Back in AccessTheWebAsync. The following statement suspends progress in `AccessTheWebAsync` when `getStringTask` is awaited. -```cs +```csharp string urlContents = await getStringTask; ``` @@ -336,7 +336,7 @@ string urlContents = await getStringTask; The following statement assigns this task to the `getLengthTask` variable. -```cs +```csharp Task getLengthTask = AccessTheWebAsync(); ``` @@ -352,7 +352,7 @@ FOUR: Back in startButton_Click. Progress in `startButton_Click` is suspended when `getLengthTask` is awaited. The following assignment statement suspends `startButton_Click` until `AccessTheWebAsync` is complete. -```cs +```csharp int contentLength = await getLengthTask; ``` @@ -396,7 +396,7 @@ SIX: Back in startButton_Click. The await expression retrieves from `getLengthTask` the integer value that’s the operand of the return statement in `AccessTheWebAsync`. The following statement assigns that value to the `contentLength` variable. -```cs +```csharp int contentLength = await getLengthTask; ``` diff --git a/docs/csharp/programming-guide/concepts/async/handling-reentrancy-in-async-apps.md b/docs/csharp/programming-guide/concepts/async/handling-reentrancy-in-async-apps.md index acff72c1ec54e..718d810606400 100644 --- a/docs/csharp/programming-guide/concepts/async/handling-reentrancy-in-async-apps.md +++ b/docs/csharp/programming-guide/concepts/async/handling-reentrancy-in-async-apps.md @@ -119,7 +119,7 @@ TOTAL bytes returned: 890591 The following code shows these changes, which are marked with asterisks. You can add the changes to the code at the end of this topic, or you can download the finished app from [Async Samples: Reentrancy in .NET Desktop Apps](http://go.microsoft.com/fwlink/?LinkId=266571). The project name is DisableStartButton. -```cs +```csharp private async void StartButton_Click(object sender, RoutedEventArgs e) { // This line is commented out to make the results clearer in the output. @@ -155,7 +155,7 @@ private async void StartButton_Click(object sender, RoutedEventArgs e) 1. Declare a variable, `cts`, that’s in scope for all methods. - ```cs + ```csharp public partial class MainWindow : Window // Or class MainPage { // *** Declare a System.Threading.CancellationTokenSource. @@ -164,7 +164,7 @@ private async void StartButton_Click(object sender, RoutedEventArgs e) 2. In `StartButton_Click`, determine whether an operation is already underway. If the value of `cts` is null, no operation is already active. If the value isn't null, the operation that is already running is canceled. - ```cs + ```csharp // *** If a download process is already underway, cancel it. if (cts != null) { @@ -174,7 +174,7 @@ private async void StartButton_Click(object sender, RoutedEventArgs e) 3. Set `cts` to a different value that represents the current process. - ```cs + ```csharp // *** Now set cts to a new value that you can use to cancel the current process // if the button is chosen again. CancellationTokenSource newCTS = new CancellationTokenSource(); @@ -183,7 +183,7 @@ private async void StartButton_Click(object sender, RoutedEventArgs e) 4. At the end of `StartButton_Click`, the current process is complete, so set the value of `cts` back to null. - ```cs + ```csharp // *** When the process is complete, signal that another process can begin. if (cts == newCTS) cts = null; @@ -191,7 +191,7 @@ private async void StartButton_Click(object sender, RoutedEventArgs e) The following code shows all the changes in `StartButton_Click`. The additions are marked with asterisks. -```cs +```csharp private async void StartButton_Click(object sender, RoutedEventArgs e) { // This line is commented out to make the results clearer in the output. @@ -238,7 +238,7 @@ private async void StartButton_Click(object sender, RoutedEventArgs e) The following code shows these changes, which are marked with asterisks. -```cs +```csharp // *** Provide a parameter for the CancellationToken from StartButton_Click. async Task AccessTheWebAsync(CancellationToken ct) { @@ -398,7 +398,7 @@ TOTAL bytes returned: 920526 #### Global Definitions The sample code contains the following two global declarations that are visible from all methods. -```cs +```csharp public partial class MainWindow : Window // Class MainPage in Windows Store app. { // ***Declare the following variables where all methods can access them. @@ -411,7 +411,7 @@ public partial class MainWindow : Window // Class MainPage in Windows Store app #### The Click Event Handler The event handler, `StartButton_Click`, increments the group letter each time the user chooses the **Start** button. Then the handler calls `AccessTheWebAsync` to run the downloading operation. -```cs +```csharp private async void StartButton_Click(object sender, RoutedEventArgs e) { // ***Verify that each group's results are displayed together, and that @@ -442,7 +442,7 @@ private async void StartButton_Click(object sender, RoutedEventArgs e) `FinishOneGroupAsync` returns a task that's assigned to `pendingWork` in `AccessTheWebAsync`. That value prevents interruption by another operation before the task is complete. -```cs +```csharp private async Task AccessTheWebAsync(char grp) { HttpClient client = new HttpClient(); @@ -472,7 +472,7 @@ private async Task AccessTheWebAsync(char grp) The first statement in `FinishOneGroupAsync` uses `pendingWork` to make sure that entering the method doesn't interfere with an operation that is already in the display process or that's already waiting. If such an operation is in progress, the entering operation must wait its turn. -```cs +```csharp private async Task FinishOneGroupAsync(List urls, Task[] contentTasks, char grp) { // ***Wait for the previous group to finish displaying results. @@ -595,7 +595,7 @@ private async Task FinishOneGroupAsync(List urls, Task[] content 7. In the **XAML** view of MainWindow.xaml, replace the code with the following code. - ```cs + ```csharp urls, Task[] content 10. In MainWindow.xaml.cs, replace the code with the following code. - ```cs + ```csharp using System; using System.Collections.Generic; using System.Linq; diff --git a/docs/csharp/programming-guide/concepts/async/how-to-extend-the-async-walkthrough-by-using-task-whenall.md b/docs/csharp/programming-guide/concepts/async/how-to-extend-the-async-walkthrough-by-using-task-whenall.md index b0c2fbeb95bf0..dfc5757f758c6 100644 --- a/docs/csharp/programming-guide/concepts/async/how-to-extend-the-async-walkthrough-by-using-task-whenall.md +++ b/docs/csharp/programming-guide/concepts/async/how-to-extend-the-async-walkthrough-by-using-task-whenall.md @@ -44,7 +44,7 @@ You can improve the performance of the async solution in [Walkthrough: Accessing The `ProcessURLAsync` method consolidates the actions in the body of the `foreach` loop in `SumPageSizesAsync` in the original walkthrough. The method asynchronously downloads the contents of a specified website as a byte array, and then displays and returns the length of the byte array. - ```cs + ```csharp private async Task ProcessURLAsync(string url) { var byteArray = await GetURLContentsAsync(url); @@ -55,7 +55,7 @@ You can improve the performance of the async solution in [Walkthrough: Accessing 2. Comment out or delete the `foreach` loop in `SumPageSizesAsync`, as the following code shows. - ```cs + ```csharp //var total = 0; //foreach (var url in urlList) //{ @@ -78,7 +78,7 @@ You can improve the performance of the async solution in [Walkthrough: Accessing Add the following code to method `SumPageSizesAsync` after the declaration of `urlList`. - ```cs + ```csharp // Create a query. IEnumerable> downloadTasksQuery = from url in urlList select ProcessURLAsync(url); @@ -91,7 +91,7 @@ You can improve the performance of the async solution in [Walkthrough: Accessing In the following example, the `await` expression awaits the completion of the single task that `WhenAll` returns. The expression evaluates to an array of integers, where each integer is the length of a downloaded website. Add the following code to `SumPageSizesAsync`, just after the code that you added in the previous step. - ```cs + ```csharp // Await the completion of all the running tasks. int[] lengths = await Task.WhenAll(downloadTasks); @@ -102,7 +102,7 @@ You can improve the performance of the async solution in [Walkthrough: Accessing 5. Finally, use the method to calculate the sum of the lengths of all the websites. Add the following line to `SumPageSizesAsync`. - ```cs + ```csharp int total = lengths.Sum(); ``` @@ -118,7 +118,7 @@ You can improve the performance of the async solution in [Walkthrough: Accessing The only difference from the `ProcessURLAsync` method in the previous procedure is the use of the instance, `client`. - ```cs + ```csharp async Task ProcessURL(string url, HttpClient client) { byte[] byteArray = await client.GetByteArrayAsync(url); @@ -129,7 +129,7 @@ You can improve the performance of the async solution in [Walkthrough: Accessing 2. Comment out or delete the `For Each` or `foreach` loop in `SumPageSizesAsync`, as the following code shows. - ```cs + ```csharp //var total = 0; //foreach (var url in urlList) //{ @@ -153,7 +153,7 @@ You can improve the performance of the async solution in [Walkthrough: Accessing Add the following code to method `SumPageSizesAsync` after the declaration of `client` and `urlList`. - ```cs + ```csharp // Create a query. IEnumerable> downloadTasksQuery = from url in urlList select ProcessURL(url, client); @@ -166,7 +166,7 @@ You can improve the performance of the async solution in [Walkthrough: Accessing In the following example, the `await` expression awaits the completion of the single task that `WhenAll` returns. When complete, the `await` expression evaluates to an array of integers, where each integer is the length of a downloaded website. Add the following code to `SumPageSizesAsync`, just after the code that you added in the previous step. - ```cs + ```csharp // Await the completion of all the running tasks. int[] lengths = await Task.WhenAll(downloadTasks); @@ -177,7 +177,7 @@ You can improve the performance of the async solution in [Walkthrough: Accessing 5. Finally, use the method to get the sum of the lengths of all the websites. Add the following line to `SumPageSizesAsync`. - ```cs + ```csharp int total = lengths.Sum(); ``` @@ -188,7 +188,7 @@ You can improve the performance of the async solution in [Walkthrough: Accessing ## Example The following code shows the extensions to the project that uses the `GetURLContentsAsync` method to download content from the web. -```cs +```csharp // Add the following using directives, and add a reference for System.Net.Http. using System.Net.Http; using System.IO; @@ -330,7 +330,7 @@ namespace AsyncExampleWPF_WhenAll ## Example The following code shows the extensions to the project that uses method `HttpClient.GetByteArrayAsync` to download content from the web. -```cs +```csharp // Add the following using directives, and add a reference for System.Net.Http. using System.Net.Http; using System.IO; diff --git a/docs/csharp/programming-guide/concepts/async/how-to-make-multiple-web-requests-in-parallel-by-using-async-and-await.md b/docs/csharp/programming-guide/concepts/async/how-to-make-multiple-web-requests-in-parallel-by-using-async-and-await.md index 93beb6a417c0f..7805b1899b294 100644 --- a/docs/csharp/programming-guide/concepts/async/how-to-make-multiple-web-requests-in-parallel-by-using-async-and-await.md +++ b/docs/csharp/programming-guide/concepts/async/how-to-make-multiple-web-requests-in-parallel-by-using-async-and-await.md @@ -25,13 +25,13 @@ translation.priority.mt: # How to: Make Multiple Web Requests in Parallel by Using async and await (C#) In an async method, tasks are started when they’re created. The [await](../../../../csharp/language-reference/keywords/await.md) operator is applied to the task at the point in the method where processing can’t continue until the task finishes. Often a task is awaited as soon as it’s created, as the following example shows. -```cs +```csharp var result = await someWebAccessMethodAsync(url); ``` However, you can separate creating the task from awaiting the task if your program has other work to accomplish that doesn’t depend on the completion of the task. -```cs +```csharp // The following line creates and starts the task. var myTask = someWebAccessMethodAsync(url); @@ -71,7 +71,7 @@ var result = await myTask; 2. Copy the following code, and paste it into the body of `startButton_Click` in MainWindow.xaml.cs. - ```cs + ```csharp resultsTextBox.Clear(); await CreateMultipleTasksAsync(); resultsTextBox.Text += "\r\n\r\nControl returned to startButton_Click.\r\n"; @@ -87,7 +87,7 @@ var result = await myTask; Copy the following methods, and paste them after the `startButton_Click` event handler in MainWindow.xaml.cs. - ```cs + ```csharp async Task ProcessURLAsync(string url, HttpClient client) { var byteArray = await client.GetByteArrayAsync(url); @@ -119,7 +119,7 @@ var result = await myTask; Copy the following method, and paste it into your solution. - ```cs + ```csharp private async Task CreateMultipleTasksAsync() { // Declare an HttpClient object, and increase the buffer size. The @@ -156,7 +156,7 @@ var result = await myTask; ## Example The following code contains the full example. -```cs +```csharp using System; using System.Collections.Generic; using System.Linq; diff --git a/docs/csharp/programming-guide/concepts/async/index.md b/docs/csharp/programming-guide/concepts/async/index.md index 4c224f258b8a3..886611df19cf4 100644 --- a/docs/csharp/programming-guide/concepts/async/index.md +++ b/docs/csharp/programming-guide/concepts/async/index.md @@ -54,7 +54,7 @@ Asynchrony proves especially valuable for applications that access the UI thread You can find a complete Windows Presentation Foundation (WPF) example file at the end of this topic, and you can download the sample from [Async Sample: Example from "Asynchronous Programming with Async and Await"](http://go.microsoft.com/fwlink/?LinkID=261549). -```cs +```csharp // Three things to note in the signature: // - The method has an async modifier. // - The return type is Task or Task. (See "Return Types" section.) @@ -87,7 +87,7 @@ async Task AccessTheWebAsync() If `AccessTheWebAsync` doesn't have any work that it can do between calling `GetStringAsync` and awaiting its completion, you can simplify your code by calling and awaiting in the following single statement. -```cs +```csharp string urlContents = await client.GetStringAsync(); ``` @@ -187,7 +187,7 @@ string urlContents = await client.GetStringAsync(); The following example shows how you declare and call a method that returns a or a . -```cs +```csharp // Signature specifies Task async Task TaskOfTResult_MethodAsync() { @@ -265,7 +265,7 @@ await Task_MethodAsync(); ## Complete Example The following code is the MainWindow.xaml.cs file from the Windows Presentation Foundation (WPF) application that this topic discusses. You can download the sample from [Async Sample: Example from "Asynchronous Programming with Async and Await"](http://go.microsoft.com/fwlink/p/?LinkID=261549). -```cs +```csharp using System; using System.Collections.Generic; using System.Linq; diff --git a/docs/csharp/programming-guide/concepts/async/start-multiple-async-tasks-and-process-them-as-they-complete.md b/docs/csharp/programming-guide/concepts/async/start-multiple-async-tasks-and-process-them-as-they-complete.md index d3905e3f2f879..8da7e49657c39 100644 --- a/docs/csharp/programming-guide/concepts/async/start-multiple-async-tasks-and-process-them-as-they-complete.md +++ b/docs/csharp/programming-guide/concepts/async/start-multiple-async-tasks-and-process-them-as-they-complete.md @@ -56,7 +56,7 @@ By using , The **CancelAfterOneTask** project already includes a query that, when executed, creates a collection of tasks. Each call to `ProcessURLAsync` in the following code returns a where `TResult` is an integer. -```cs +```csharp IEnumerable> downloadTasksQuery = from url in urlList select ProcessURL(url, client, ct); ``` @@ -65,7 +65,7 @@ IEnumerable> downloadTasksQuery = - Execute the query by applying instead of . - ```cs + ```csharp List> downloadTasks = downloadTasksQuery.ToList(); ``` @@ -73,19 +73,19 @@ IEnumerable> downloadTasksQuery = 1. Awaits a call to `WhenAny` to identify the first task in the collection to finish its download. - ```cs + ```csharp Task firstFinishedTask = await Task.WhenAny(downloadTasks); ``` 2. Removes that task from the collection. - ```cs + ```csharp downloadTasks.Remove(firstFinishedTask); ``` 3. Awaits `firstFinishedTask`, which is returned by a call to `ProcessURLAsync`. The `firstFinishedTask` variable is a where `TReturn` is an integer. The task is already complete, but you await it to retrieve the length of the downloaded website, as the following example shows. - ```cs + ```csharp int length = await firstFinishedTask; resultsTextBox.Text += String.Format("\r\nLength of the download: {0}", length); ``` @@ -102,7 +102,7 @@ IEnumerable> downloadTasksQuery = You can download the project from [Async Sample: Fine Tuning Your Application](http://go.microsoft.com/fwlink/?LinkId=255046). -```cs +```csharp using System; using System.Collections.Generic; using System.Linq; diff --git a/docs/csharp/programming-guide/concepts/async/using-async-for-file-access.md b/docs/csharp/programming-guide/concepts/async/using-async-for-file-access.md index d03bd5cc3bd0a..865419e059fca 100644 --- a/docs/csharp/programming-guide/concepts/async/using-async-for-file-access.md +++ b/docs/csharp/programming-guide/concepts/async/using-async-for-file-access.md @@ -42,7 +42,7 @@ You can use the async feature to access files. By using the async feature, you c In the following examples, include the following `using` statements. -```cs +```csharp using System; using System.Collections.Generic; using System.Diagnostics; @@ -59,7 +59,7 @@ using System.Threading.Tasks; ## Writing Text The following example writes text to a file. At each await statement, the method immediately exits. When the file I/O is complete, the method resumes at the statement that follows the await statement. Note that the async modifier is in the definition of methods that use the await statement. -```cs +```csharp public async void ProcessWrite() { string filePath = @"temp2.txt"; @@ -83,7 +83,7 @@ private async Task WriteTextAsync(string filePath, string text) The original example has the statement `await sourceStream.WriteAsync(encodedText, 0, encodedText.Length);`, which is a contraction of the following two statements: -```cs +```csharp Task theTask = sourceStream.WriteAsync(encodedText, 0, encodedText.Length); await theTask; ``` @@ -93,7 +93,7 @@ await theTask; ## Reading Text The following example reads text from a file. The text is buffered and, in this case, placed into a . Unlike in the previous example, the evaluation of the await produces a value. The method returns a \<>, so the evaluation of the await produces an `Int32` value (`numRead`) after the operation completes. For more information, see [Async Return Types (C#)](../../../../csharp/programming-guide/concepts/async/async-return-types.md). -```cs +```csharp public async void ProcessRead() { string filePath = @"temp2.txt"; @@ -144,7 +144,7 @@ private async Task ReadTextAsync(string filePath) Note that any performance boost is almost entirely from the parallel processing and not the asynchronous processing. The advantages of asynchrony are that it doesn’t tie up multiple threads, and that it doesn’t tie up the user interface thread. -```cs +```csharp public async void ProcessWriteMult() { string folder = @"tempfolder\"; diff --git a/docs/csharp/programming-guide/concepts/async/walkthrough-accessing-the-web-by-using-async-and-await.md b/docs/csharp/programming-guide/concepts/async/walkthrough-accessing-the-web-by-using-async-and-await.md index aa81a5c9421d4..7ef5b807542b9 100644 --- a/docs/csharp/programming-guide/concepts/async/walkthrough-accessing-the-web-by-using-async-and-await.md +++ b/docs/csharp/programming-guide/concepts/async/walkthrough-accessing-the-web-by-using-async-and-await.md @@ -127,7 +127,7 @@ You can write asynchronous programs more easily and intuitively by using feature 2. Add the following `using` directives at the top of the code file if they’re not already present. - ```cs + ```csharp using System.Net.Http; using System.Net; using System.IO; @@ -140,7 +140,7 @@ You can write asynchronous programs more easily and intuitively by using feature 2. In MainWindow.xaml.cs, copy the following code into the body of `startButton_Click`: - ```cs + ```csharp resultsTextBox.Clear(); SumPageSizes(); resultsTextBox.Text += "\r\nControl returned to startButton_Click."; @@ -160,7 +160,7 @@ You can write asynchronous programs more easily and intuitively by using feature Copy the following four methods, and then paste them under the `startButton_Click` event handler in MainWindow.xaml.cs: - ```cs + ```csharp private void SumPageSizes() { // Make a list of web addresses. @@ -278,7 +278,7 @@ You can write asynchronous programs more easily and intuitively by using feature Change the method that's called in the third line of `GetURLContents` from `GetResponse` to the asynchronous, task-based method. - ```cs + ```csharp using (WebResponse response = webReq.GetResponseAsync()) ``` @@ -286,7 +286,7 @@ You can write asynchronous programs more easily and intuitively by using feature To retrieve the `WebResponse` value from the task, apply an [await](../../../../csharp/language-reference/keywords/await.md) operator to the call to `GetResponseAsync`, as the following code shows. - ```cs + ```csharp using (WebResponse response = await webReq.GetResponseAsync()) ``` @@ -294,7 +294,7 @@ You can write asynchronous programs more easily and intuitively by using feature The previous statement can be separated into the following two statements to clarify what happens. - ```cs + ```csharp //Task responseTask = webReq.GetResponseAsync(); //using (WebResponse response = await responseTask) ``` @@ -309,13 +309,13 @@ You can write asynchronous programs more easily and intuitively by using feature - The `CopyTo` or `CopyToAsync` method copies bytes to its argument, `content`, and doesn’t return a meaningful value. In the synchronous version, the call to `CopyTo` is a simple statement that doesn't return a value. The asynchronous version, `CopyToAsync`, returns a . The task functions like "Task(void)" and enables the method to be awaited. Apply `Await` or `await` to the call to `CopyToAsync`, as the following code shows. - ```cs + ```csharp await responseStream.CopyToAsync(content); ``` The previous statement abbreviates the following two lines of code. - ```cs + ```csharp // CopyToAsync returns a Task, not a Task. //Task copyTask = responseStream.CopyToAsync(content); @@ -326,7 +326,7 @@ You can write asynchronous programs more easily and intuitively by using feature 4. All that remains to be done in `GetURLContents` is to adjust the method signature. You can use the `await` operator only in methods that are marked with the [async](../../../../csharp/language-reference/keywords/async.md) modifier. Add the modifier to mark the method as an *async method*, as the following code shows. - ```cs + ```csharp private async byte[] GetURLContents(string url) ``` @@ -342,7 +342,7 @@ You can write asynchronous programs more easily and intuitively by using feature The following code shows these changes. - ```cs + ```csharp private async Task GetURLContentsAsync(string url) ``` @@ -359,13 +359,13 @@ You can write asynchronous programs more easily and intuitively by using feature The following code shows these changes. - ```cs + ```csharp byte[] urlContents = await GetURLContentsAsync(url); ``` The previous assignment abbreviates the following two lines of code. - ```cs + ```csharp // GetURLContentsAsync returns a Task. At completion, the task // produces a byte array. //Task getContentsTask = GetURLContentsAsync(url); @@ -382,7 +382,7 @@ You can write asynchronous programs more easily and intuitively by using feature The following code shows these changes. - ```cs + ```csharp private async Task SumPageSizesAsync() ``` @@ -399,7 +399,7 @@ You can write asynchronous programs more easily and intuitively by using feature As in previous procedures, you can convert the call by using one statement or two statements. The following code shows these changes. - ```cs + ```csharp // One-step async call. await SumPageSizesAsync(); @@ -410,14 +410,14 @@ You can write asynchronous programs more easily and intuitively by using feature 3. To prevent accidentally reentering the operation, add the following statement at the top of `startButton_Click` to disable the **Start** button. - ```cs + ```csharp // Disable the button until the operation is complete. startButton.IsEnabled = false; ``` You can reenable the button at the end of the event handler. - ```cs + ```csharp // Reenable the button in case you want to run the operation again. startButton.IsEnabled = true; ``` @@ -426,7 +426,7 @@ You can write asynchronous programs more easily and intuitively by using feature 4. Finally, add the `async` modifier to the declaration so that the event handler can await `SumPagSizesAsync`. - ```cs + ```csharp private async void startButton_Click(object sender, RoutedEventArgs e) ``` @@ -452,7 +452,7 @@ You can write asynchronous programs more easily and intuitively by using feature The first step is to create an `HttpClient` object in method `SumPageSizesAsync`. Add the following declaration at the start of the method. - ```cs + ```csharp // Declare an HttpClient object and increase the buffer size. The // default buffer size is 65,536. HttpClient client = @@ -461,7 +461,7 @@ You can write asynchronous programs more easily and intuitively by using feature 2. In `SumPageSizesAsync,` replace the call to your `GetURLContentsAsync` method with a call to the `HttpClient` method. - ```cs + ```csharp byte[] urlContents = await client.GetByteArrayAsync(url); ``` @@ -474,7 +474,7 @@ You can write asynchronous programs more easily and intuitively by using feature ## Example The following code contains the full example of the conversion from a synchronous to an asynchronous solution by using the asynchronous `GetURLContentsAsync` method that you wrote. Notice that it strongly resembles the original, synchronous solution. -```cs +```csharp using System; using System.Collections.Generic; using System.Linq; @@ -623,7 +623,7 @@ namespace AsyncExampleWPF The following code contains the full example of the solution that uses the `HttpClient` method, `GetByteArrayAsync`. -```cs +```csharp using System; using System.Collections.Generic; using System.Linq; diff --git a/docs/csharp/programming-guide/concepts/attributes/accessing-attributes-by-using-reflection.md b/docs/csharp/programming-guide/concepts/attributes/accessing-attributes-by-using-reflection.md index 58e96cd239bc9..99e7fce9441bd 100644 --- a/docs/csharp/programming-guide/concepts/attributes/accessing-attributes-by-using-reflection.md +++ b/docs/csharp/programming-guide/concepts/attributes/accessing-attributes-by-using-reflection.md @@ -27,14 +27,14 @@ The fact that you can define custom attributes and place them in your source cod An attribute specification such as: -```cs +```csharp [Author("P. Ackerman", version = 1.1)] class SampleClass ``` is conceptually equivalent to this: -```cs +```csharp Author anonymousAuthorObject = new Author("P. Ackerman"); anonymousAuthorObject.version = 1.1; ``` @@ -44,7 +44,7 @@ anonymousAuthorObject.version = 1.1; ## Example Here is a complete example. A custom attribute is defined, applied to several entities, and retrieved via reflection. -```cs +```csharp // Multiuse attribute. [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, diff --git a/docs/csharp/programming-guide/concepts/attributes/attributeusage.md b/docs/csharp/programming-guide/concepts/attributes/attributeusage.md index 124cd0a6908a6..577d58a8f5b5b 100644 --- a/docs/csharp/programming-guide/concepts/attributes/attributeusage.md +++ b/docs/csharp/programming-guide/concepts/attributes/attributeusage.md @@ -25,7 +25,7 @@ translation.priority.mt: # AttributeUsage (C#) Determines how a custom attribute class can be used. `AttributeUsage` is an attribute that can be applied to custom attribute definitions to control how the new attribute can be applied. The default settings look like this when applied explicitly: -```cs +```csharp [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = false, Inherited = true)] @@ -36,29 +36,29 @@ class NewAttribute : System.Attribute { } The `AllowMultiple` and `Inherited` arguments are optional, so this code has the same effect: -```cs +```csharp [System.AttributeUsage(System.AttributeTargets.All)] class NewAttribute : System.Attribute { } ``` The first `AttributeUsage` argument must be one or more elements of the enumeration. Multiple target types can be linked together with the OR operator, like this: -```cs +```csharp using System; ``` -```cs +```csharp [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] class NewPropertyOrFieldAttribute : Attribute { } ``` If the `AllowMultiple` argument is set to `true`, then the resulting attribute can be applied more than once to a single entity, like this: -```cs +```csharp using System; ``` -```cs +```csharp [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] class MultiUseAttr : Attribute { } @@ -74,11 +74,11 @@ class Class2 { } If `Inherited` is set to `false`, then the attribute is not inherited by classes that are derived from a class that is attributed. For example: -```cs +```csharp using System; ``` -```cs +```csharp [AttributeUsage(AttributeTargets.Class, Inherited = false)] class Attr1 : Attribute { } @@ -98,11 +98,11 @@ class DClass : BClass { } ## Example The following example demonstrates the effect of the `Inherited` and `AllowMultiple` arguments to the `AttributeUsage` attribute, and how the custom attributes applied to a class can be enumerated. -```cs +```csharp using System; ``` -```cs +```csharp // Create some custom attributes: [AttributeUsage(System.AttributeTargets.Class, Inherited = false)] class A1 : System.Attribute { } diff --git a/docs/csharp/programming-guide/concepts/attributes/common-attributes.md b/docs/csharp/programming-guide/concepts/attributes/common-attributes.md index dc3efeef84c93..9304affcbf6f9 100644 --- a/docs/csharp/programming-guide/concepts/attributes/common-attributes.md +++ b/docs/csharp/programming-guide/concepts/attributes/common-attributes.md @@ -36,7 +36,7 @@ This topic describes the attributes that are most commonly used in C# programs. ## Global Attributes Most attributes are applied to specific language elements such as classes or methods; however, some attributes are global—they apply to an entire assembly or module. For example, the attribute can be used to embed version information into an assembly, like this: -```cs +```csharp [assembly: AssemblyVersion("1.0.0.0")] ``` @@ -88,7 +88,7 @@ This topic describes the attributes that are most commonly used in C# programs. ## Obsolete Attribute The `Obsolete` attribute marks a program entity as one that is no longer recommended for use. Each use of an entity marked obsolete will subsequently generate a warning or an error, depending on how the attribute is configured. For example: -```cs +```csharp [System.Obsolete("use class B")] class A { @@ -106,7 +106,7 @@ class B The string provided as the first argument to attribute constructor will be displayed as part of the warning or error. For example, when you use it with the previous definitions, the following code generates two warnings and one error: -```cs +```csharp // Generates 2 warnings: // A a = new A(); @@ -129,7 +129,7 @@ b.NewMethod(); In this example, `Conditional` is applied to a method to enable or disable the display of program-specific diagnostic information: -```cs +```csharp #define TRACE_ON using System; using System.Diagnostics; @@ -157,7 +157,7 @@ public class ProgramClass The `Conditional` attribute is often used with the `DEBUG` identifier to enable trace and logging features for debug builds but not in release builds, like this: -```cs +```csharp [Conditional("DEBUG")] static void DebugMethod() { @@ -166,7 +166,7 @@ static void DebugMethod() When a method marked as conditional is called, the presence or absence of the specified preprocessing symbol determines whether the call is included or omitted. If the symbol is defined, the call is included; otherwise, the call is omitted. Using `Conditional` is a cleaner, more elegant, and less error-prone alternative to enclosing methods inside `#if…#endif` blocks, like this: -```cs +```csharp #if DEBUG void ConditionalMethod() { @@ -179,7 +179,7 @@ static void DebugMethod() ### Using Multiple Identifiers If a method has multiple `Conditional` attributes, a call to the method is included if at least one of the conditional symbols is defined (in other words, the symbols are logically linked together by using the OR operator). In this example, the presence of either `A` or `B` will result in a method call: -```cs +```csharp [Conditional("A"), Conditional("B")] static void DoIfAorB() { @@ -189,7 +189,7 @@ static void DoIfAorB() To achieve the effect of logically linking symbols by using the AND operator, you can define serial conditional methods. For example, the second method below will execute only if both `A` and `B` are defined: -```cs +```csharp Shared Sub DoIfA() DoIfAandB() @@ -204,7 +204,7 @@ End Sub ### Using Conditional with Attribute Classes The `Conditional` attribute can also be applied to an attribute class definition. In this example, the custom attribute `Documentation` will only add information to the metadata if DEBUG is defined. -```cs +```csharp [Conditional("DEBUG")] public class Documentation : System.Attribute { diff --git a/docs/csharp/programming-guide/concepts/attributes/creating-custom-attributes.md b/docs/csharp/programming-guide/concepts/attributes/creating-custom-attributes.md index b26f767df753f..cc58d387aad1e 100644 --- a/docs/csharp/programming-guide/concepts/attributes/creating-custom-attributes.md +++ b/docs/csharp/programming-guide/concepts/attributes/creating-custom-attributes.md @@ -25,7 +25,7 @@ translation.priority.mt: # Creating Custom Attributes (C#) You can create your own custom attributes by defining an attribute class, a class that derives directly or indirectly from , which makes identifying attribute definitions in metadata fast and easy. Suppose you want to tag types with the name of the programmer who wrote the type. You might define a custom `Author` attribute class: -```cs +```csharp [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct) ] @@ -46,7 +46,7 @@ public class Author : System.Attribute You could use this new attribute as follows: -```cs +```csharp [Author("P. Ackerman", version = 1.1)] class SampleClass { @@ -56,7 +56,7 @@ class SampleClass `AttributeUsage` has a named parameter, `AllowMultiple`, with which you can make a custom attribute single-use or multiuse. In the following code example, a multiuse attribute is created. -```cs +```csharp [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct, AllowMultiple = true) // multiuse attribute @@ -66,7 +66,7 @@ public class Author : System.Attribute In the following code example, multiple attributes of the same type are applied to a class. -```cs +```csharp [Author("P. Ackerman", version = 1.1)] [Author("R. Koch", version = 1.2)] class SampleClass diff --git a/docs/csharp/programming-guide/concepts/attributes/how-to-create-a-c-cpp-union-by-using-attributes.md b/docs/csharp/programming-guide/concepts/attributes/how-to-create-a-c-cpp-union-by-using-attributes.md index 7e63b11457bd1..88300f15aeb9f 100644 --- a/docs/csharp/programming-guide/concepts/attributes/how-to-create-a-c-cpp-union-by-using-attributes.md +++ b/docs/csharp/programming-guide/concepts/attributes/how-to-create-a-c-cpp-union-by-using-attributes.md @@ -28,7 +28,7 @@ By using attributes you can customize how structs are laid out in memory. For ex ## Example In this code segment, all of the fields of `TestUnion` start at the same location in memory. -```cs +```csharp // Add a using directive for System.Runtime.InteropServices. [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)] @@ -51,7 +51,7 @@ By using attributes you can customize how structs are laid out in memory. For ex ## Example The following is another example where fields start at different explicitly set locations. -```cs +```csharp // Add a using directive for System.Runtime.InteropServices. [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)] diff --git a/docs/csharp/programming-guide/concepts/attributes/index.md b/docs/csharp/programming-guide/concepts/attributes/index.md index 9f9ecdf862bbb..332194da094fa 100644 --- a/docs/csharp/programming-guide/concepts/attributes/index.md +++ b/docs/csharp/programming-guide/concepts/attributes/index.md @@ -40,7 +40,7 @@ Attributes provide a powerful method of associating metadata, or declarative inf In this example, the attribute is used to apply a specific characteristic to a class: -```cs +```csharp [System.Serializable] public class SampleClass { @@ -50,22 +50,22 @@ public class SampleClass A method with the attribute is declared like this: -```cs +```csharp using System.Runtime.InteropServices; ``` -```cs +```csharp [System.Runtime.InteropServices.DllImport("user32.dll")] extern static void SampleMethod(); ``` More than one attribute can be placed on a declaration: -```cs +```csharp using System.Runtime.InteropServices; ``` -```cs +```csharp void MethodA([In][Out] ref double x) { } void MethodB([Out][In] ref double x) { } void MethodC([In, Out] ref double x) { } @@ -73,7 +73,7 @@ void MethodC([In, Out] ref double x) { } Some attributes can be specified more than once for a given entity. An example of such a multiuse attribute is : -```cs +```csharp [Conditional("DEBUG"), Conditional("TEST1")] void TraceMethod() { @@ -87,7 +87,7 @@ void TraceMethod() ### Attribute Parameters Many attributes have parameters, which can be positional, unnamed, or named. Any positional parameters must be specified in a certain order and cannot be omitted; named parameters are optional and can be specified in any order. Positional parameters are specified first. For example, these three attributes are equivalent: -```cs +```csharp [DllImport("user32.dll")] [DllImport("user32.dll", SetLastError=false, ExactSpelling=false)] [DllImport("user32.dll", ExactSpelling=false, SetLastError=false)] @@ -100,7 +100,7 @@ void TraceMethod() To explicitly identify an attribute target, use the following syntax: -```cs +```csharp [target : attribute-list] ``` @@ -120,7 +120,7 @@ void TraceMethod() The following example shows how to apply attributes to assemblies and modules. For more information, see [Common Attributes (C#)](../../../../csharp/programming-guide/concepts/attributes/common-attributes.md). -```cs +```csharp using System; using System.Reflection; [assembly: AssemblyTitleAttribute("Production assembly 4")] @@ -129,7 +129,7 @@ using System.Reflection; The following example shows how to apply attributes to methods, method parameters, and method return values in C#. -```cs +```csharp // default: applies to method [SomeAttr] int Method1() { return 0; } diff --git a/docs/csharp/programming-guide/concepts/caller-information.md b/docs/csharp/programming-guide/concepts/caller-information.md index 2f56edf4f27d7..da17b867d91a5 100644 --- a/docs/csharp/programming-guide/concepts/caller-information.md +++ b/docs/csharp/programming-guide/concepts/caller-information.md @@ -36,7 +36,7 @@ By using Caller Info attributes, you can obtain information about the caller to ## Example The following example shows how to use Caller Info attributes. On each call to the `TraceMessage` method, the caller information is substituted as arguments to the optional parameters. -```cs +```csharp public void DoProcessing() { TraceMessage("Something happened."); diff --git a/docs/csharp/programming-guide/concepts/collections.md b/docs/csharp/programming-guide/concepts/collections.md index 22fefc04af082..4c76e0eb455f7 100644 --- a/docs/csharp/programming-guide/concepts/collections.md +++ b/docs/csharp/programming-guide/concepts/collections.md @@ -64,7 +64,7 @@ For many applications, you want to create and manage groups of related objects. The following example creates a list of strings and then iterates through the strings by using a or [foreach](../../../csharp/language-reference/keywords/foreach-in.md) statement. -```cs +```csharp // Create a list of strings. var salmons = new List(); salmons.Add("chinook"); @@ -84,7 +84,7 @@ foreach (var salmon in salmons) The following example is the same as the previous example, except a collection initializer is used to add elements to the collection. -```cs +```csharp // Create a list of strings by using a // collection initializer. var salmons = new List { "chinook", "coho", "pink", "sockeye" }; @@ -101,7 +101,7 @@ foreach (var salmon in salmons) The following example iterates through the elements of a collection by using `for` instead of `foreach`. -```cs +```csharp // Create a list of strings by using a // collection initializer. var salmons = new List { "chinook", "coho", "pink", "sockeye" }; @@ -115,7 +115,7 @@ for (var index = 0; index < salmons.Count; index++) The following example removes an element from the collection by specifying the object to remove. -```cs +```csharp // Create a list of strings by using a // collection initializer. var salmons = new List { "chinook", "coho", "pink", "sockeye" }; @@ -134,7 +134,7 @@ foreach (var salmon in salmons) The following example removes elements from a generic list. Instead of a `foreach` statement, a [for](../../../csharp/language-reference/keywords/for.md) statement that iterates in descending order is used. This is because the method causes elements after a removed element to have a lower index value. -```cs +```csharp var numbers = new List { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Remove odd numbers. @@ -158,7 +158,7 @@ numbers.ForEach( For the type of elements in the , you can also define your own class. In the following example, the `Galaxy` class that is used by the is defined in the code. -```cs +```csharp private static void IterateThroughList() { var theGalaxies = new List @@ -247,7 +247,7 @@ public class Galaxy The following example creates a `Dictionary` collection and iterates through the dictionary by using a `foreach` statement. -```cs +```csharp private static void IterateThruDictionary() { Dictionary elements = BuildDictionary(); @@ -296,7 +296,7 @@ public class Element To instead use a collection initializer to build the `Dictionary` collection, you can replace the `BuildDictionary` and `AddToDictionary` methods with the following method. -```cs +```csharp private static Dictionary BuildDictionary2() { return new Dictionary @@ -315,7 +315,7 @@ private static Dictionary BuildDictionary2() The following example uses the method and the property of `Dictionary` to quickly find an item by key. The `Item` property enables you to access an item in the `elements` collection by using the `elements[symbol]` in C#. -```cs +```csharp private static void FindInDictionary(string symbol) { Dictionary elements = BuildDictionary(); @@ -334,7 +334,7 @@ private static void FindInDictionary(string symbol) The following example instead uses the method quickly find an item by key. -```cs +```csharp private static void FindInDictionary2(string symbol) { Dictionary elements = BuildDictionary(); @@ -353,7 +353,7 @@ private static void FindInDictionary2(string symbol) The following example runs a LINQ query against a generic `List`. The LINQ query returns a different collection that contains the results. -```cs +```csharp private static void ShowLINQ() { List elements = BuildList(); @@ -402,7 +402,7 @@ public class Element In the `ListCars` method, the `cars.Sort()` statement sorts the list. This call to the method of the causes the `CompareTo` method to be called automatically for the `Car` objects in the `List`. -```cs +```csharp private static void ListCars() { var cars = new List @@ -482,7 +482,7 @@ public class Car : IComparable The `GetEnumerator` method returns an instance of the `ColorEnumerator` class. `ColorEnumerator` implements the interface, which requires that the property, method, and method be implemented. -```cs +```csharp private static void ListColors() { var colors = new AllColors(); @@ -563,7 +563,7 @@ public class Color The following example uses an iterator method. The iterator method has a `yield return` statement that is inside a [for](../../../csharp/language-reference/keywords/for.md) loop. In the `ListEvenNumbers` method, each iteration of the `foreach` statement body creates a call to the iterator method, which proceeds to the next `yield return` statement. -```cs +```csharp private static void ListEvenNumbers() { foreach (int number in EvenSequence(5, 18)) diff --git a/docs/csharp/programming-guide/concepts/covariance-contravariance/creating-variant-generic-interfaces.md b/docs/csharp/programming-guide/concepts/covariance-contravariance/creating-variant-generic-interfaces.md index 7b2789fafc862..90b150b8796be 100644 --- a/docs/csharp/programming-guide/concepts/covariance-contravariance/creating-variant-generic-interfaces.md +++ b/docs/csharp/programming-guide/concepts/covariance-contravariance/creating-variant-generic-interfaces.md @@ -38,7 +38,7 @@ You can declare generic type parameters in interfaces as covariant or contravari - The type is used only as a return type of interface methods and not used as a type of method arguments. This is illustrated in the following example, in which the type `R` is declared covariant. - ```cs + ```csharp interface ICovariant { R GetSomething(); @@ -50,7 +50,7 @@ You can declare generic type parameters in interfaces as covariant or contravari There is one exception to this rule. If you have a contravariant generic delegate as a method parameter, you can use the type as a generic type parameter for the delegate. This is illustrated by the type `R` in the following example. For more information, see [Variance in Delegates (C#)](../../../../csharp/programming-guide/concepts/covariance-contravariance/variance-in-delegates.md) and [Using Variance for Func and Action Generic Delegates (C#)](../../../../csharp/programming-guide/concepts/covariance-contravariance/using-variance-for-func-and-action-generic-delegates.md). - ```cs + ```csharp interface ICovariant { void DoSomething(Action callback); @@ -59,7 +59,7 @@ You can declare generic type parameters in interfaces as covariant or contravari - The type is not used as a generic constraint for the interface methods. This is illustrated in the following code. - ```cs + ```csharp interface ICovariant { // The following statement generates a compiler error @@ -71,7 +71,7 @@ You can declare generic type parameters in interfaces as covariant or contravari You can declare a generic type parameter contravariant by using the `in` keyword. The contravariant type can be used only as a type of method arguments and not as a return type of interface methods. The contravariant type can also be used for generic constraints. The following code shows how to declare a contravariant interface and use a generic constraint for one of its methods. -```cs +```csharp interface IContravariant { void SetSomething(A sampleArg); @@ -83,7 +83,7 @@ interface IContravariant It is also possible to support both covariance and contravariance in the same interface, but for different type parameters, as shown in the following code example. -```cs +```csharp interface IVariant { R GetSomething(); @@ -95,7 +95,7 @@ interface IVariant ## Implementing Variant Generic Interfaces You implement variant generic interfaces in classes by using the same syntax that is used for invariant interfaces. The following code example shows how to implement a covariant interface in a generic class. -```cs +```csharp interface ICovariant { R GetSomething(); @@ -112,7 +112,7 @@ class SampleImplementation : ICovariant Classes that implement variant interfaces are invariant. For example, consider the following code. -```cs +```csharp // The interface is covariant. ICovariant