From a6d0a68c2614262b592e48f872fa2c8b3a32b046 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 16 Jun 2026 10:48:47 -0700 Subject: [PATCH 1/6] redirects and toc files --- .openpublishing.redirection.fundamentals.json | 756 +++++++++++++++++- docs/csharp/toc.yml | 4 - docs/framework/app-domains/toc.yml | 4 - docs/framework/network-programming/toc.yml | 4 - docs/fundamentals/toc.yml | 348 -------- docs/navigate/advanced-programming/toc.yml | 42 - docs/navigate/data-access/toc.yml | 56 -- docs/navigate/security/toc.yml | 10 - docs/navigate/tools-diagnostics/toc.yml | 8 - 9 files changed, 718 insertions(+), 514 deletions(-) diff --git a/.openpublishing.redirection.fundamentals.json b/.openpublishing.redirection.fundamentals.json index a8f85bfb5e996..53e11f7e38ff3 100644 --- a/.openpublishing.redirection.fundamentals.json +++ b/.openpublishing.redirection.fundamentals.json @@ -24,10 +24,6 @@ "source_path_from_root": "/docs/fundamentals/code-analysis/quality-rules/ca1867.md", "redirect_url": "/dotnet/fundamentals/code-analysis/quality-rules/ca1865-ca1867" }, - { - "source_path_from_root": "/docs/fundamentals/code-analysis/quality-rules/singlefile-warnings.md", - "redirect_url": "/dotnet/core/deploying/single-file/warnings/overview" - }, { "source_path_from_root": "/docs/fundamentals/code-analysis/quality-rules/il3000.md", "redirect_url": "/dotnet/core/deploying/single-file/warnings/il3000" @@ -48,6 +44,10 @@ "source_path_from_root": "/docs/fundamentals/code-analysis/quality-rules/publish-warnings.md", "redirect_url": "/dotnet/core/deploying/single-file/warnings/overview" }, + { + "source_path_from_root": "/docs/fundamentals/code-analysis/quality-rules/singlefile-warnings.md", + "redirect_url": "/dotnet/core/deploying/single-file/warnings/overview" + }, { "source_path_from_root": "/docs/fundamentals/code-analysis/style-rules/code-block-preferences.md", "redirect_url": "/dotnet/fundamentals/code-analysis/style-rules/language-rules" @@ -165,40 +165,20 @@ "redirect_url": "/dotnet/fundamentals/code-analysis/style-rules/language-rules" }, { - "source_path_from_root": "/docs/fundamentals/networking/httpclient.md", - "redirect_url": "/dotnet/fundamentals/networking/http/httpclient" - }, - { - "source_path_from_root": "/docs/standard/commandline/customize-help.md", - "redirect_url": "/dotnet/standard/commandline/how-to-customize-help" - }, - { - "source_path_from_root": "/docs/standard/commandline/define-commands.md", - "redirect_url": "/dotnet/standard/commandline/syntax#commands" - }, - { - "source_path_from_root": "/docs/standard/commandline/dependency-injection.md", - "redirect_url": "/dotnet/standard/commandline/migration-guide-2.0.0-beta5#invocation" - }, - { - "source_path_from_root": "/docs/standard/commandline/handle-termination.md", - "redirect_url": "/dotnet/standard/commandline/how-to-parse-and-invoke#process-termination-timeout" - }, - { - "source_path_from_root": "/docs/standard/commandline/model-binding.md", - "redirect_url": "/dotnet/standard/commandline/how-to-parse-and-invoke" + "source_path_from_root": "/docs/fundamentals/networking/http/http-autoclient.md", + "redirect_url": "/dotnet/fundamentals/networking/http/http-overview" }, { - "source_path_from_root": "/docs/standard/commandline/use-middleware.md", - "redirect_url": "/dotnet/standard/commandline/migration-guide-2.0.0-beta5#configuration" + "source_path_from_root": "/docs/fundamentals/networking/httpclient-guidelines.md", + "redirect_url": "/dotnet/fundamentals/networking/http/httpclient-guidelines" }, { - "source_path_from_root": "/docs/standard/commandline/tab-completion.md", - "redirect_url": "/dotnet/standard/commandline/how-to-enable-tab-completion" + "source_path_from_root": "/docs/fundamentals/networking/httpclient.md", + "redirect_url": "/dotnet/fundamentals/networking/http/httpclient" }, { - "source_path_from_root": "/docs/fundamentals/networking/httpclient-guidelines.md", - "redirect_url": "/dotnet/fundamentals/networking/http/httpclient-guidelines" + "source_path_from_root": "/docs/fundamentals/networking/networking-telemetry.md", + "redirect_url": "/dotnet/fundamentals/networking/telemetry/overview" }, { "source_path_from_root": "/docs/fundamentals/package-validation/baseline-version-validator.md", @@ -225,10 +205,6 @@ "redirect_url": "/dotnet/fundamentals/apicompat/package-validation/overview", "redirect_document_id": true }, - { - "source_path_from_root": "/docs/fundamentals/networking/networking-telemetry.md", - "redirect_url": "/dotnet/fundamentals/networking/telemetry/overview" - }, { "source_path_from_root": "/docs/fundamentals/productivity/code-analysis.md", "redirect_url": "/dotnet/fundamentals/code-analysis/overview" @@ -241,6 +217,74 @@ "source_path_from_root": "/docs/fundamentals/reflection/reflection.md", "redirect_url": "/dotnet/fundamentals/reflection/overview" }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/microsoft-win32-registry.md", + "redirect_url": "/dotnet/api/microsoft.win32.registry" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-accessviolationexception.md", + "redirect_url": "/dotnet/api/system.accessviolationexception" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-appcontext.md", + "redirect_url": "/dotnet/api/system.appcontext" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-appdomain-unhandledexception.md", + "redirect_url": "/dotnet/api/system.appdomain.unhandledexception" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-boolean.md", + "redirect_url": "/dotnet/api/system.boolean" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-byte.md", + "redirect_url": "/dotnet/api/system.byte" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-char.md", + "redirect_url": "/dotnet/api/system.char" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md", + "redirect_url": "/dotnet/api/system.collections.generic.hashset-1" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md", + "redirect_url": "/dotnet/api/system.collections.generic.list-1" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md", + "redirect_url": "/dotnet/api/system.collections.objectmodel.keyedcollection-2.changeitemkey" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-collections-objectmodel-observablecollection{t}.md", + "redirect_url": "/dotnet/api/system.collections.objectmodel.observablecollection-1" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-console.md", + "redirect_url": "/dotnet/api/system.console" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-convert.md", + "redirect_url": "/dotnet/api/system.convert" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-data-commandbehavior.md", + "redirect_url": "/dotnet/api/system.data.commandbehavior" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-data-datacolumn-expression.md", + "redirect_url": "/dotnet/api/system.data.datacolumn.expression" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-data-dataset.md", + "redirect_url": "/dotnet/api/system.data.dataset" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-data-datatable.md", + "redirect_url": "/dotnet/api/system.data.datatable" + }, { "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-data-linq-dataloadoptions.md", "redirect_url": "/dotnet/framework/data/adonet/sql/linq/" @@ -249,6 +293,618 @@ "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-data-linq-mapping-tableattribute.md", "redirect_url": "/dotnet/framework/data/adonet/sql/linq/" }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-datetime-tobinary.md", + "redirect_url": "/dotnet/api/system.datetime.tobinary" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-datetime-tryparse.md", + "redirect_url": "/dotnet/api/system.datetime.tryparse" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-datetime.md", + "redirect_url": "/dotnet/api/system.datetime" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-decimal.md", + "redirect_url": "/dotnet/api/system.decimal" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-delegate-createdelegate.md", + "redirect_url": "/dotnet/api/system.delegate.createdelegate" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-diagnostics-performancecountertype.md", + "redirect_url": "/dotnet/api/system.diagnostics.performancecountertype" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-diagnostics-processstartinfo-useshellexecute.md", + "redirect_url": "/dotnet/api/system.diagnostics.processstartinfo.useshellexecute" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md", + "redirect_url": "/dotnet/api/system.diagnostics.tracing.eventsource" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventwritteneventargs.md", + "redirect_url": "/dotnet/api/system.diagnostics.tracing.eventwritteneventargs" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-double-compareto.md", + "redirect_url": "/dotnet/api/system.double.compareto" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-double-epsilon.md", + "redirect_url": "/dotnet/api/system.double.epsilon" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-double-equals.md", + "redirect_url": "/dotnet/api/system.double.equals" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-double.md", + "redirect_url": "/dotnet/api/system.double" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-drawing-drawing2d-matrix.md", + "redirect_url": "/dotnet/api/system.drawing.drawing2d.matrix" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md", + "redirect_url": "/dotnet/api/system.dynamic.expandoobject" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-enum.md", + "redirect_url": "/dotnet/api/system.enum" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-environment-getenvironmentvariable.md", + "redirect_url": "/dotnet/api/system.environment.getenvironmentvariable" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-exception-data.md", + "redirect_url": "/dotnet/api/system.exception.data" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-exception-message.md", + "redirect_url": "/dotnet/api/system.exception.message" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-exception.md", + "redirect_url": "/dotnet/api/system.exception" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-flagsattribute.md", + "redirect_url": "/dotnet/api/system.flagsattribute" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-gc.md", + "redirect_url": "/dotnet/api/system.gc" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md", + "redirect_url": "/dotnet/api/system.globalization.compareinfo" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-compareoptions.md", + "redirect_url": "/dotnet/api/system.globalization.compareoptions" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder-ctor.md", + "redirect_url": "/dotnet/api/system.globalization.cultureandregioninfobuilder.ctor" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder.md", + "redirect_url": "/dotnet/api/system.globalization.cultureandregioninfobuilder" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentculture.md", + "redirect_url": "/dotnet/api/system.globalization.cultureinfo.currentculture" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentuiculture.md", + "redirect_url": "/dotnet/api/system.globalization.cultureinfo.currentuiculture" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-invariantculture.md", + "redirect_url": "/dotnet/api/system.globalization.cultureinfo.invariantculture" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md", + "redirect_url": "/dotnet/api/system.globalization.cultureinfo" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md", + "redirect_url": "/dotnet/api/system.globalization.datetimeformatinfo" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md", + "redirect_url": "/dotnet/api/system.globalization.numberformatinfo" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-persiancalendar.md", + "redirect_url": "/dotnet/api/system.globalization.persiancalendar" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-regioninfo.md", + "redirect_url": "/dotnet/api/system.globalization.regioninfo" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md", + "redirect_url": "/dotnet/api/system.globalization.sortkey" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md", + "redirect_url": "/dotnet/api/system.globalization.sortversion" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-iasyncdisposable.md", + "redirect_url": "/dotnet/api/system.iasyncdisposable" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-idisposable.md", + "redirect_url": "/dotnet/api/system.idisposable" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-int32.md", + "redirect_url": "/dotnet/api/system.int32" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-int64.md", + "redirect_url": "/dotnet/api/system.int64" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-invalidcastexception.md", + "redirect_url": "/dotnet/api/system.invalidcastexception" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-invalidoperationexception.md", + "redirect_url": "/dotnet/api/system.invalidoperationexception" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-io-filestream.md", + "redirect_url": "/dotnet/api/system.io.filestream" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-io-filesystemwatcher.md", + "redirect_url": "/dotnet/api/system.io.filesystemwatcher" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-linq-expressions-binaryexpression.md", + "redirect_url": "/dotnet/api/system.linq.expressions.binaryexpression" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-linq-expressions-expression-add.md", + "redirect_url": "/dotnet/api/system.linq.expressions.expression.add" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-midpointrounding.md", + "redirect_url": "/dotnet/api/system.midpointrounding" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-net-ftpwebrequest-proxy.md", + "redirect_url": "/dotnet/api/system.net.ftpwebrequest.proxy" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-net-http-httpclient.md", + "redirect_url": "/dotnet/api/system.net.http.httpclient" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-net-http-httpclienthandler.md", + "redirect_url": "/dotnet/api/system.net.http.httpclienthandler" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-net-httplistener.md", + "redirect_url": "/dotnet/api/system.net.httplistener" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-net-sockets-socket.md", + "redirect_url": "/dotnet/api/system.net.sockets.socket" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-notimplementedexception.md", + "redirect_url": "/dotnet/api/system.notimplementedexception" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-notsupportedexception.md", + "redirect_url": "/dotnet/api/system.notsupportedexception" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-nullable.md", + "redirect_url": "/dotnet/api/system.nullable" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-nullable{t}.md", + "redirect_url": "/dotnet/api/system.nullable-1" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-numerics-biginteger.md", + "redirect_url": "/dotnet/api/system.numerics.biginteger" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-numerics-complex.md", + "redirect_url": "/dotnet/api/system.numerics.complex" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-object-equals.md", + "redirect_url": "/dotnet/api/system.object.equals" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-object-finalize.md", + "redirect_url": "/dotnet/api/system.object.finalize" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-object-gethashcode.md", + "redirect_url": "/dotnet/api/system.object.gethashcode" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-object-tostring.md", + "redirect_url": "/dotnet/api/system.object.tostring" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-object.md", + "redirect_url": "/dotnet/api/system.object" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-random.md", + "redirect_url": "/dotnet/api/system.random" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-context-customreflectioncontext.md", + "redirect_url": "/dotnet/api/system.reflection.context.customreflectioncontext" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-emit-assemblybuilder.md", + "redirect_url": "/dotnet/api/system.reflection.emit.assemblybuilder" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicilinfo.md", + "redirect_url": "/dotnet/api/system.reflection.emit.dynamicilinfo" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md", + "redirect_url": "/dotnet/api/system.reflection.emit.dynamicmethod.createdelegate" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md", + "redirect_url": "/dotnet/api/system.reflection.emit.dynamicmethod.ctor" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md", + "redirect_url": "/dotnet/api/system.reflection.emit.dynamicmethod.getilgenerator" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md", + "redirect_url": "/dotnet/api/system.reflection.emit.dynamicmethod.invoke" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md", + "redirect_url": "/dotnet/api/system.reflection.emit.dynamicmethod.issecuritycritical" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod.md", + "redirect_url": "/dotnet/api/system.reflection.emit.dynamicmethod" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-emit-methodbuilder.md", + "redirect_url": "/dotnet/api/system.reflection.emit.methodbuilder" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-emit-persistedassemblybuilder.md", + "redirect_url": "/dotnet/api/system.reflection.emit.persistedassemblybuilder" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-emit-typebuilder.md", + "redirect_url": "/dotnet/api/system.reflection.emit.typebuilder" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-reflection-portableexecutable-debugdirectoryentrytype.md", + "redirect_url": "/dotnet/api/system.reflection.portableexecutable.debugdirectoryentrytype" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-resources-missingmanifestresourceexception.md", + "redirect_url": "/dotnet/api/system.resources.missingmanifestresourceexception" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-resources-neutralresourceslanguageattribute.md", + "redirect_url": "/dotnet/api/system.resources.neutralresourceslanguageattribute" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-ctor.md", + "redirect_url": "/dotnet/api/system.resources.resourcemanager.ctor" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getobject.md", + "redirect_url": "/dotnet/api/system.resources.resourcemanager.getobject" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getstring.md", + "redirect_url": "/dotnet/api/system.resources.resourcemanager.getstring" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md", + "redirect_url": "/dotnet/api/system.resources.resourcemanager" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-resources-resourcereader.md", + "redirect_url": "/dotnet/api/system.resources.resourcereader" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-resources-satellitecontractversionattribute.md", + "redirect_url": "/dotnet/api/system.resources.satellitecontractversionattribute" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-internalsvisibletoattribute.md", + "redirect_url": "/dotnet/api/system.runtime.compilerservices.internalsvisibletoattribute" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-runtimehelpers-gethashcode.md", + "redirect_url": "/dotnet/api/system.runtime.compilerservices.runtimehelpers.gethashcode" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-interopservices-comexception.md", + "redirect_url": "/dotnet/api/system.runtime.interopservices.comexception" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-interopservices-comwrappers.md", + "redirect_url": "/dotnet/api/system.runtime.interopservices.comwrappers" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-interopservices-icustommarshaler.md", + "redirect_url": "/dotnet/api/system.runtime.interopservices.icustommarshaler" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-interopservices-marshal-getactiveobject.md", + "redirect_url": "/dotnet/api/system.runtime.interopservices.marshal.getactiveobject" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-interopservices-safehandle.md", + "redirect_url": "/dotnet/api/system.runtime.interopservices.safehandle" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-loader-assemblyloadcontext.md", + "redirect_url": "/dotnet/api/system.runtime.loader.assemblyloadcontext" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractattribute.md", + "redirect_url": "/dotnet/api/system.runtime.serialization.datacontractattribute" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractserializer.md", + "redirect_url": "/dotnet/api/system.runtime.serialization.datacontractserializer" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-serialization-iextensibledataobject.md", + "redirect_url": "/dotnet/api/system.runtime.serialization.iextensibledataobject" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-serialization-xsddatacontractexporter.md", + "redirect_url": "/dotnet/api/system.runtime.serialization.xsddatacontractexporter" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-runtime-versioning-componentguaranteesattribute.md", + "redirect_url": "/dotnet/api/system.runtime.versioning.componentguaranteesattribute" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-security-cryptography-rsacryptoserviceprovider.md", + "redirect_url": "/dotnet/api/system.security.cryptography.rsacryptoserviceprovider" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-security-cryptography-rsaparameters.md", + "redirect_url": "/dotnet/api/system.security.cryptography.rsaparameters" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-security-cryptography-xml-signedxml.md", + "redirect_url": "/dotnet/api/system.security.cryptography.xml.signedxml" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-security-securestring.md", + "redirect_url": "/dotnet/api/system.security.securestring" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-single-compareto.md", + "redirect_url": "/dotnet/api/system.single.compareto" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-single-epsilon.md", + "redirect_url": "/dotnet/api/system.single.epsilon" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-single-equals.md", + "redirect_url": "/dotnet/api/system.single.equals" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-single.md", + "redirect_url": "/dotnet/api/system.single" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-span{t}.md", + "redirect_url": "/dotnet/api/system.span-1" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-string-ctor.md", + "redirect_url": "/dotnet/api/system.string.ctor" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-string-format.md", + "redirect_url": "/dotnet/api/system.string.format" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-string-intern.md", + "redirect_url": "/dotnet/api/system.string.intern" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-string-isnullorempty.md", + "redirect_url": "/dotnet/api/system.string.isnullorempty" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-string.md", + "redirect_url": "/dotnet/api/system.string" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-stringcomparer.md", + "redirect_url": "/dotnet/api/system.stringcomparer" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-text-encoding-default.md", + "redirect_url": "/dotnet/api/system.text.encoding.default" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-text-encoding.md", + "redirect_url": "/dotnet/api/system.text.encoding" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex-match.md", + "redirect_url": "/dotnet/api/system.text.regularexpressions.regex.match" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex.md", + "redirect_url": "/dotnet/api/system.text.regularexpressions.regex" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-text-rune.md", + "redirect_url": "/dotnet/api/system.text.rune" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md", + "redirect_url": "/dotnet/api/system.text.stringbuilder" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-threading-monitor-wait.md", + "redirect_url": "/dotnet/api/system.threading.monitor.wait" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-threading-monitor.md", + "redirect_url": "/dotnet/api/system.threading.monitor" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-threading-readerwriterlockslim.md", + "redirect_url": "/dotnet/api/system.threading.readerwriterlockslim" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-threading-tasks-task.md", + "redirect_url": "/dotnet/api/system.threading.tasks.task" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-threading-tasks-taskscheduler.md", + "redirect_url": "/dotnet/api/system.threading.tasks.taskscheduler" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-threading-thread.md", + "redirect_url": "/dotnet/api/system.threading.thread" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-timespan-parse.md", + "redirect_url": "/dotnet/api/system.timespan.parse" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-timespan-tryparse.md", + "redirect_url": "/dotnet/api/system.timespan.tryparse" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-timespan.md", + "redirect_url": "/dotnet/api/system.timespan" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-type-getproperty.md", + "redirect_url": "/dotnet/api/system.type.getproperty" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-type-gettype.md", + "redirect_url": "/dotnet/api/system.type.gettype" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-type-makegenerictype.md", + "redirect_url": "/dotnet/api/system.type.makegenerictype" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-type.md", + "redirect_url": "/dotnet/api/system.type" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-typeinitializationexception.md", + "redirect_url": "/dotnet/api/system.typeinitializationexception" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-uri.md", + "redirect_url": "/dotnet/api/system.uri" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-version.md", + "redirect_url": "/dotnet/api/system.version" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-linq-xname.md", + "redirect_url": "/dotnet/api/system.xml.linq.xname" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-linq-xnamespace.md", + "redirect_url": "/dotnet/api/system.xml.linq.xnamespace" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-schema-xmlschemaset.md", + "redirect_url": "/dotnet/api/system.xml.schema.xmlschemaset" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-serialization-codegenerationoptions.md", + "redirect_url": "/dotnet/api/system.xml.serialization.codegenerationoptions" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-serialization-xmlserializer.md", + "redirect_url": "/dotnet/api/system.xml.serialization.xmlserializer" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmlconvert.md", + "redirect_url": "/dotnet/api/system.xml.xmlconvert" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmldocument.md", + "redirect_url": "/dotnet/api/system.xml.xmldocument" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmlreader-create.md", + "redirect_url": "/dotnet/api/system.xml.xmlreader.create" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmlreader.md", + "redirect_url": "/dotnet/api/system.xml.xmlreader" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-dtdprocessing.md", + "redirect_url": "/dotnet/api/system.xml.xmlreadersettings.dtdprocessing" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-schemas.md", + "redirect_url": "/dotnet/api/system.xml.xmlreadersettings.schemas" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings.md", + "redirect_url": "/dotnet/api/system.xml.xmlreadersettings" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmlresolver.md", + "redirect_url": "/dotnet/api/system.xml.xmlresolver" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmlsecureresolver.md", + "redirect_url": "/dotnet/api/system.xml.xmlsecureresolver" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmltextreader.md", + "redirect_url": "/dotnet/api/system.xml.xmltextreader" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmltextwriter.md", + "redirect_url": "/dotnet/api/system.xml.xmltextwriter" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xmlwriter.md", + "redirect_url": "/dotnet/api/system.xml.xmlwriter" + }, + { + "source_path_from_root": "/docs/fundamentals/runtime-libraries/system-xml-xsl-xslcompiledtransform.md", + "redirect_url": "/dotnet/api/system.xml.xsl.xslcompiledtransform" + }, { "source_path_from_root": "/docs/fundamentals/syslib-diagnostics/syslib1004.md", "redirect_url": "/dotnet/fundamentals/syslib-diagnostics/source-generator-overview" @@ -594,8 +1250,32 @@ "redirect_url": "/dotnet/toc/tools-diagnostics/index" }, { - "source_path_from_root": "/docs/fundamentals/networking/http/http-autoclient.md", - "redirect_url": "/dotnet/fundamentals/networking/http/http-overview" + "source_path_from_root": "/docs/standard/commandline/customize-help.md", + "redirect_url": "/dotnet/standard/commandline/how-to-customize-help" + }, + { + "source_path_from_root": "/docs/standard/commandline/define-commands.md", + "redirect_url": "/dotnet/standard/commandline/syntax#commands" + }, + { + "source_path_from_root": "/docs/standard/commandline/dependency-injection.md", + "redirect_url": "/dotnet/standard/commandline/migration-guide-2.0.0-beta5#invocation" + }, + { + "source_path_from_root": "/docs/standard/commandline/handle-termination.md", + "redirect_url": "/dotnet/standard/commandline/how-to-parse-and-invoke#process-termination-timeout" + }, + { + "source_path_from_root": "/docs/standard/commandline/model-binding.md", + "redirect_url": "/dotnet/standard/commandline/how-to-parse-and-invoke" + }, + { + "source_path_from_root": "/docs/standard/commandline/tab-completion.md", + "redirect_url": "/dotnet/standard/commandline/how-to-enable-tab-completion" + }, + { + "source_path_from_root": "/docs/standard/commandline/use-middleware.md", + "redirect_url": "/dotnet/standard/commandline/migration-guide-2.0.0-beta5#configuration" } ] } diff --git a/docs/csharp/toc.yml b/docs/csharp/toc.yml index e943cb48281bd..d73629ec9f0f5 100644 --- a/docs/csharp/toc.yml +++ b/docs/csharp/toc.yml @@ -412,10 +412,6 @@ items: href: advanced-topics/expression-trees/debugging-expression-trees-in-visual-studio.md - name: DebugView Syntax href: advanced-topics/expression-trees/debugview-syntax.md - - name: Supplemental API - Expression class add method - href: ../fundamentals/runtime-libraries/system-linq-expressions-expression-add.md - - name: Supplemental API - BinaryExpression class - href: ../fundamentals/runtime-libraries/system-linq-expressions-binaryexpression.md - name: Native interoperability items: - name: Overview diff --git a/docs/framework/app-domains/toc.yml b/docs/framework/app-domains/toc.yml index 80b9314f6029e..d28b02187bbc5 100644 --- a/docs/framework/app-domains/toc.yml +++ b/docs/framework/app-domains/toc.yml @@ -48,9 +48,5 @@ items: href: shadow-copy-assemblies.md - name: "How to: Receive First-Chance Exception Notifications" href: how-to-receive-first-chance-exception-notifications.md - - name: Supplemental API remarks - items: - - name: AppDomain.UnhandledException event - href: ../../fundamentals/runtime-libraries/system-appdomain-unhandledexception.md - name: Run Intranet Applications in Full Trust href: running-intranet-applications-in-full-trust.md diff --git a/docs/framework/network-programming/toc.yml b/docs/framework/network-programming/toc.yml index 8fa29f66309d9..c4e3963ae0b64 100644 --- a/docs/framework/network-programming/toc.yml +++ b/docs/framework/network-programming/toc.yml @@ -49,10 +49,6 @@ items: href: how-to-upload-files-with-ftp.md - name: List Directory Contents with FTP href: how-to-list-directory-contents-with-ftp.md - - name: Supplemental API remarks - items: - - name: FtpWebRequest.Proxy property - href: ../../fundamentals/runtime-libraries/system-net-ftpwebrequest-proxy.md - name: UDP href: using-udp-services.md - name: Security in Network Programming diff --git a/docs/fundamentals/toc.yml b/docs/fundamentals/toc.yml index 0f12cf034b3b4..d6fd331470f0c 100644 --- a/docs/fundamentals/toc.yml +++ b/docs/fundamentals/toc.yml @@ -239,37 +239,10 @@ items: href: ../standard/base-types/type-conversion.md - name: Type conversion tables href: ../standard/base-types/conversion-tables.md - - name: Supplemental API remarks - items: - - name: Convert class - href: runtime-libraries/system-convert.md - name: Choose between anonymous and tuple types href: ../standard/base-types/choosing-between-anonymous-and-tuple.md - name: Core .NET libraries overview href: ../standard/class-library-overview.md - - name: Supplemental API remarks - items: - - name: System.Object class - items: - - name: Type remarks - href: runtime-libraries/system-object.md - displayName: object - - name: Equals method - href: runtime-libraries/system-object-equals.md - - name: Finalize method - href: runtime-libraries/system-object-finalize.md - - name: GetHashCode method - href: runtime-libraries/system-object-gethashcode.md - - name: ToString method - href: runtime-libraries/system-object-tostring.md - - name: Nullability - items: - - name: Supplemental API remarks - items: - - name: Nullable class - href: runtime-libraries/system-nullable.md - - name: Nullable class - href: runtime-libraries/system-nullable{t}.md - name: Generic types items: - name: Overview @@ -305,35 +278,11 @@ items: href: ../standard/collections/hashtable-and-dictionary-collection-types.md - name: Thread-safe collections href: ../standard/collections/thread-safe/index.md?toc=/dotnet/fundamentals/toc.json&bc=/dotnet/breadcrumb/toc.json - - name: Supplemental API remarks - items: - - name: HashSet class - href: runtime-libraries/system-collections-generic-hashset{t}.md - - name: KeyedCollection class - items: - - name: ChangeItemKey method - href: runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md - - name: List class - href: runtime-libraries/system-collections-generic-list{t}.md - - name: ObservableCollection class - href: runtime-libraries/system-collections-objectmodel-observablecollection{t}.md - name: Delegates and lambdas items: - name: Overview href: ../standard/delegates-lambdas.md displayName: delegates,lambdas - - name: Supplemental API remarks - items: - - name: Delegate.CreateDelegate method - href: runtime-libraries/system-delegate-createdelegate.md - - name: Enumerations - items: - - name: Supplemental API remarks - items: - - name: Enum class - href: runtime-libraries/system-enum.md - - name: FlagsAttribute class - href: runtime-libraries/system-flagsattribute.md - name: Events items: - name: Overview @@ -381,72 +330,11 @@ items: href: ../standard/exceptions/handling-com-interop-exceptions.md - name: Best practices href: ../standard/exceptions/best-practices-for-exceptions.md - - name: Supplemental API remarks - items: - - name: AccessViolationException class - href: runtime-libraries/system-accessviolationexception.md - - name: Exception class - items: - - name: Type remarks - href: runtime-libraries/system-exception.md - displayName: exception - - name: Data property - href: runtime-libraries/system-exception-data.md - - name: Message property - href: runtime-libraries/system-exception-message.md - - name: InvalidCastException class - href: runtime-libraries/system-invalidcastexception.md - - name: InvalidOperationException class - href: runtime-libraries/system-invalidoperationexception.md - - name: NotImplementedException class - href: runtime-libraries/system-notimplementedexception.md - - name: NotSupportedException class - href: runtime-libraries/system-notsupportedexception.md - - name: TypeInitializationException class - href: runtime-libraries/system-typeinitializationexception.md - name: Numeric types items: - name: Overview displayName: numeric types href: ../standard/numerics.md - - name: Supplemental API remarks - items: - - name: Boolean struct - href: runtime-libraries/system-boolean.md - - name: Byte struct - href: runtime-libraries/system-byte.md - - name: Decimal struct - href: runtime-libraries/system-decimal.md - - name: Double struct - items: - - name: Type remarks - href: runtime-libraries/system-double.md - displayName: system.double,double - - name: CompareTo method - href: runtime-libraries/system-double-compareto.md - - name: Equals method - href: runtime-libraries/system-double-equals.md - - name: Epsilon property - href: runtime-libraries/system-double-epsilon.md - - name: Int32 struct - href: runtime-libraries/system-int32.md - - name: Int64 struct - href: runtime-libraries/system-int64.md - - name: BigInteger struct - href: runtime-libraries/system-numerics-biginteger.md - - name: Complex struct - href: runtime-libraries/system-numerics-complex.md - - name: Single struct - items: - - name: Type remarks - href: runtime-libraries/system-single.md - displayName: single - - name: CompareTo method - href: runtime-libraries/system-single-compareto.md - - name: Epsilon property - href: runtime-libraries/system-single-epsilon.md - - name: Equals method - href: runtime-libraries/system-single-equals.md - name: Dates, times, and time zones items: - name: Overview @@ -504,26 +392,6 @@ items: href: ../standard/datetime/save-time-zones-to-an-embedded-resource.md - name: Restore time zones from an embedded resource href: ../standard/datetime/restore-time-zones-from-an-embedded-resource.md - - name: Supplemental API remarks - items: - - name: DateTime struct - items: - - name: Type remarks - href: runtime-libraries/system-datetime.md - displayName: datetime - - name: ToBinary method - href: runtime-libraries/system-datetime-tobinary.md - - name: TryParse method - href: runtime-libraries/system-datetime-tryparse.md - - name: TimeSpan struct - items: - - name: Type remarks - href: runtime-libraries/system-timespan.md - displayName: timespan - - name: Parse method - href: runtime-libraries/system-timespan-parse.md - - name: TryParse method - href: runtime-libraries/system-timespan-tryparse.md - name: Attributes items: - name: Overview @@ -543,10 +411,6 @@ items: href: ../standard/memory-and-spans/index.md - name: Memory and Span usage guidelines href: ../standard/memory-and-spans/memory-t-usage-guidelines.md - - name: Supplemental API remarks - items: - - name: Span struct - href: runtime-libraries/system-span{t}.md - name: SIMD-enabled types href: ../standard/simd.md - name: Value tuples @@ -633,43 +497,6 @@ items: href: ../standard/base-types/parsing-datetime.md - name: Parse other strings href: ../standard/base-types/parsing-other.md - - name: Supplemental API remarks - items: - - name: String class - items: - - name: Type remarks - href: runtime-libraries/system-string.md - displayName: string - - name: Constructor - href: runtime-libraries/system-string-ctor.md - - name: Format method - href: runtime-libraries/system-string-format.md - - name: Intern method - href: runtime-libraries/system-string-intern.md - - name: IsNullOrEmpty method - href: runtime-libraries/system-string-isnullorempty.md - - name: Char struct - href: runtime-libraries/system-char.md - - name: StringComparer class - href: runtime-libraries/system-stringcomparer.md - - name: Encoding class - items: - - name: Type remarks - href: runtime-libraries/system-text-encoding.md - displayName: encoding - - name: Default property - href: runtime-libraries/system-text-encoding-default.md - - name: Regex class - items: - - name: Type remarks - href: runtime-libraries/system-text-regularexpressions-regex.md - displayName: regex - - name: Match method - href: runtime-libraries/system-text-regularexpressions-regex-match.md - - name: Rune struct - href: runtime-libraries/system-text-rune.md - - name: StringBuilder class - href: runtime-libraries/system-text-stringbuilder.md - name: Compliance items: - name: Overview @@ -903,16 +730,6 @@ items: href: ../standard/serialization/binaryformatter-security-guide.md - name: BinaryFormatter event source href: ../standard/serialization/binaryformatter-event-source.md - - name: Supplemental API remarks - items: - - name: DataContractAttribute class - href: runtime-libraries/system-runtime-serialization-datacontractattribute.md - - name: DataContractSerializer class - href: runtime-libraries/system-runtime-serialization-datacontractserializer.md - - name: IExtensibleDataObject class - href: runtime-libraries/system-runtime-serialization-iextensibledataobject.md - - name: XsdDataContractExporter class - href: runtime-libraries/system-runtime-serialization-xsddatacontractexporter.md - name: System.CommandLine items: - name: Overview @@ -923,7 +740,6 @@ items: href: ../standard/commandline/syntax.md - name: How to expanded: true - items: - name: Parse and invoke the result href: ../standard/commandline/how-to-parse-and-invoke.md - name: Customize parsing and validation @@ -1011,22 +827,10 @@ items: href: ../standard/io/buffers.md - name: Memory-mapped files href: ../standard/io/memory-mapped-files.md - - name: Supplemental API remarks - items: - - name: FileStream class - href: runtime-libraries/system-io-filestream.md - - name: FileSystemWatcher class - href: runtime-libraries/system-io-filesystemwatcher.md - - name: The System.AppContext class - href: runtime-libraries/system-appcontext.md - name: The System.Console class items: - name: Console apps href: ../standard/building-console-apps.md - - name: Supplemental API remarks - href: runtime-libraries/system-console.md - - name: The System.Random class - href: runtime-libraries/system-random.md - name: Artificial intelligence (AI) displayName: ai,microsoft.extensions.ai,ollama,openai,azure inference,ichatclient href: ../ai/microsoft-extensions-ai.md?toc=/dotnet/fundamentals/toc.json&bc=/dotnet/breadcrumb/toc.json @@ -1162,14 +966,6 @@ items: - name: Customize SNI in HTTP requests href: ../core/extensions/httpclient-sni.md displayName: networking,http,httpclient,sni,server name indication,server name indication http,server name indication httpclient,server name indication http client - - name: Supplemental API remarks - items: - - name: HttpClient class - href: runtime-libraries/system-net-http-httpclient.md - - name: HttpClientHandler class - href: runtime-libraries/system-net-http-httpclienthandler.md - - name: HttpListener class - href: runtime-libraries/system-net-httplistener.md - name: Sockets items: - name: Sockets support @@ -1181,10 +977,6 @@ items: - name: Use TcpClient and TcpListener href: networking/sockets/tcp-classes.md displayName: networking,tcp,tcp listener,tcp client - - name: Supplemental API remarks - items: - - name: Socket class - href: runtime-libraries/system-net-sockets-socket.md - name: WebSockets items: - name: WebSockets support @@ -1265,42 +1057,6 @@ items: - name: Localization href: ../core/extensions/localization.md displayName: localization,localization review,localizability review - - name: Supplemental API remarks - items: - - name: CompareInfo - href: runtime-libraries/system-globalization-compareinfo.md - - name: CompareOptions - href: runtime-libraries/system-globalization-compareoptions.md - - name: CultureAndRegionInfoBuilder - items: - - name: Type remarks - href: runtime-libraries/system-globalization-cultureandregioninfobuilder.md - displayName: cultureandregioninfobuilder - - name: Constructor - href: runtime-libraries/system-globalization-cultureandregioninfobuilder-ctor.md - - name: CultureInfo - items: - - name: Type remarks - href: runtime-libraries/system-globalization-cultureinfo.md - displayName: cultureinfo - - name: CurrentCulture property - href: runtime-libraries/system-globalization-cultureinfo-currentculture.md - - name: CurrentUICulture property - href: runtime-libraries/system-globalization-cultureinfo-currentuiculture.md - - name: InvariantCulture property - href: runtime-libraries/system-globalization-cultureinfo-invariantculture.md - - name: DateTimeFormatInfo - href: runtime-libraries/system-globalization-datetimeformatinfo.md - - name: NumberFormatInfo - href: runtime-libraries/system-globalization-numberformatinfo.md - - name: PersianCalendar - href: runtime-libraries/system-globalization-persiancalendar.md - - name: RegionInfo - href: runtime-libraries/system-globalization-regioninfo.md - - name: SortKey - href: runtime-libraries/system-globalization-sortkey.md - - name: SortVersion - href: runtime-libraries/system-globalization-sortversion.md - name: Resources in .NET apps items: - name: Overview @@ -1317,27 +1073,6 @@ items: href: ../core/extensions/package-and-deploy-resources.md - name: Retrieve resources href: ../core/extensions/retrieve-resources.md - - name: Supplemental API remarks - items: - - name: MissingManifestResourceException class - href: runtime-libraries/system-resources-missingmanifestresourceexception.md - - name: NeutralResourcesLanguageAttribute class - href: runtime-libraries/system-resources-neutralresourceslanguageattribute.md - - name: ResourceManager class - items: - - name: Type remarks - href: runtime-libraries/system-resources-resourcemanager.md - displayName: resourcemanager - - name: Constructor - href: runtime-libraries/system-resources-resourcemanager-ctor.md - - name: GetObject method - href: runtime-libraries/system-resources-resourcemanager-getobject.md - - name: GetString method - href: runtime-libraries/system-resources-resourcemanager-getstring.md - - name: ResourceReader class - href: runtime-libraries/system-resources-resourcereader.md - - name: SatelliteContractVersionAttribute class - href: runtime-libraries/system-resources-satellitecontractversionattribute.md - name: Worker services items: - name: Overview @@ -1360,58 +1095,6 @@ items: href: ../core/extensions/caching.md - name: Channels href: ../core/extensions/channels.md - - name: Math operations - items: - - name: Supplemental API remarks - items: - - name: MidpointRounding enum - href: runtime-libraries/system-midpointrounding.md - - name: The Win32.Registry class - href: runtime-libraries/microsoft-win32-registry.md - - name: The Uri class - href: runtime-libraries/system-uri.md - - name: Reflection - items: - - name: Supplemental API remarks - items: - - name: Type class - items: - - name: Type remarks - href: runtime-libraries/system-type.md - displayName: type - - name: GetProperty method - href: runtime-libraries/system-type-getproperty.md - - name: GetType method - href: runtime-libraries/system-type-gettype.md - - name: MakeGenericType method - href: runtime-libraries/system-type-makegenerictype.md - - name: The CustomReflectionContext class - href: runtime-libraries/system-reflection-context-customreflectioncontext.md - - name: Graphics - items: - - name: Supplemental API remarks - items: - - name: Matrix class - href: runtime-libraries/system-drawing-drawing2d-matrix.md - - name: The InternalsVisibleToAttribute class - href: runtime-libraries/system-runtime-compilerservices-internalsvisibletoattribute.md - - name: The RuntimeHelpers class - items: - - name: GetHashCode method - href: runtime-libraries/system-runtime-compilerservices-runtimehelpers-gethashcode.md - displayName: runtimehelpers - - name: The ComponentGuaranteesAttribute class - href: runtime-libraries/system-runtime-versioning-componentguaranteesattribute.md - - name: The AssemblyLoadContext class - href: runtime-libraries/system-runtime-loader-assemblyloadcontext.md - - name: The ProcessStartInfo class - items: - - name: UseShellExecute property - href: runtime-libraries/system-diagnostics-processstartinfo-useshellexecute.md - - name: The Environment class - items: - - name: GetEnvironmentVariable method - href: runtime-libraries/system-environment-getenvironmentvariable.md - name: Execution model items: - name: Common Language Runtime (CLR) @@ -1434,8 +1117,6 @@ items: - name: Overview displayName: versioning href: ../standard/assembly/versioning.md - - name: The System.Version class - href: runtime-libraries/system-version.md - name: Side-by-side execution href: ../standard/assembly/side-by-side-execution.md - name: Assembly file format @@ -1536,39 +1217,10 @@ items: href: reflection/how-to-define-a-generic-method-with-reflection-emit.md - name: Collectible assemblies for dynamic type generation href: reflection/collectible-assemblies.md - - name: Supplemental API remarks - items: - - name: The AssemblyBuilder class - href: runtime-libraries/system-reflection-emit-assemblybuilder.md - - name: The DynamicMethod class - items: - - name: Type remarks - href: runtime-libraries/system-reflection-emit-dynamicmethod.md - displayName: dynamicmethod - - name: CreateDelegate method - href: runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md - - name: Constructors - href: runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md - - name: GetILGenerator methods - href: runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md - - name: Invoke method - href: runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md - - name: IsSecurity* properties - href: runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md - - name: The DynamicILInfo class - href: runtime-libraries/system-reflection-emit-dynamicilinfo.md - - name: The MethodBuilder class - href: runtime-libraries/system-reflection-emit-methodbuilder.md - - name: The PersistedAssemblyBuilder class - href: runtime-libraries/system-reflection-emit-persistedassemblybuilder.md - - name: The TypeBuilder class - href: runtime-libraries/system-reflection-emit-typebuilder.md - name: Metadata and self-describing components items: - name: Overview href: ../standard/metadata-and-self-describing-components.md - - name: The DebugDirectoryEntryType enum - href: runtime-libraries/system-reflection-portableexecutable-debugdirectoryentrytype.md - name: Dependency loading items: - name: Overview diff --git a/docs/navigate/advanced-programming/toc.yml b/docs/navigate/advanced-programming/toc.yml index fc1397e62a59b..4c65b9dd3ce77 100644 --- a/docs/navigate/advanced-programming/toc.yml +++ b/docs/navigate/advanced-programming/toc.yml @@ -339,23 +339,6 @@ items: href: ../../standard/collections/thread-safe/how-to-use-arrays-of-blockingcollections.md - name: Create an object pool using a ConcurrentBag href: ../../standard/collections/thread-safe/how-to-create-an-object-pool.md - - name: Supplemental API remarks - items: - - name: The Thread class - href: ../../fundamentals/runtime-libraries/system-threading-thread.md - - name: The Task class - href: ../../fundamentals/runtime-libraries/system-threading-tasks-task.md - - name: The Monitor class - items: - - name: Type remarks - href: ../../fundamentals/runtime-libraries/system-threading-monitor.md - displayName: monitor - - name: Wait method - href: ../../fundamentals/runtime-libraries/system-threading-monitor-wait.md - - name: The ReaderWriterLockSlim class - href: ../../fundamentals/runtime-libraries/system-threading-readerwriterlockslim.md - - name: The TaskScheduler class - href: ../../fundamentals/runtime-libraries/system-threading-tasks-taskscheduler.md - name: Native interoperability items: - name: Overview @@ -425,23 +408,6 @@ items: href: ../../standard/native-interop/exceptions-interoperability.md - name: ABI support href: ../../standard/native-interop/abi-support.md - - name: Supplemental API remarks - items: - - name: The ComException class - href: ../../fundamentals/runtime-libraries/system-runtime-interopservices-comexception.md - - name: The ComWrappers class - href: ../../fundamentals/runtime-libraries/system-runtime-interopservices-comwrappers.md - - name: The ICustomMarshaler interface - href: ../../fundamentals/runtime-libraries/system-runtime-interopservices-icustommarshaler.md - - name: The Marshal class - items: - - name: GetActiveObject method - href: ../../fundamentals/runtime-libraries/system-runtime-interopservices-marshal-getactiveobject.md - displayName: marshal - - name: The SafeHandle class - href: ../../fundamentals/runtime-libraries/system-runtime-interopservices-safehandle.md - - name: The System.Dynamic.ExpandoObject class - href: ../../fundamentals/runtime-libraries/system-dynamic-expandoobject.md - name: Memory management items: - name: What is "managed code"? @@ -463,12 +429,6 @@ items: displayName: "await using, DisposeAsync, async dispose pattern, IAsyncDisposable" - name: Use objects that implement IDisposable href: ../../standard/garbage-collection/using-objects.md - - name: Supplemental API remarks - items: - - name: The IAsyncDisposable interface - href: ../../fundamentals/runtime-libraries/system-iasyncdisposable.md - - name: The IDisposable interface - href: ../../fundamentals/runtime-libraries/system-idisposable.md - name: Garbage collection items: - name: Overview @@ -498,5 +458,3 @@ items: href: ../../standard/garbage-collection/app-domain-resource-monitoring.md - name: Weak references href: ../../standard/garbage-collection/weak-references.md - - name: The System.GC class - href: ../../fundamentals/runtime-libraries/system-gc.md diff --git a/docs/navigate/data-access/toc.yml b/docs/navigate/data-access/toc.yml index e61d9e961b3bc..136babc3492a6 100644 --- a/docs/navigate/data-access/toc.yml +++ b/docs/navigate/data-access/toc.yml @@ -352,12 +352,6 @@ items: href: ../../standard/linq/sample-xml-file-consolidated-purchase-orders.md - name: Reference href: ../../standard/linq/reference.md - - name: Supplemental API remarks - items: - - name: System.Xml.Linq.XName class - href: ../../fundamentals/runtime-libraries/system-xml-linq-xname.md - - name: System.Xml.Linq.XNamespace class - href: ../../fundamentals/runtime-libraries/system-xml-linq-xnamespace.md - name: XML documents and data href: ../../standard/data/xml/index.md items: @@ -610,46 +604,6 @@ items: href: ../../standard/data/xml/converting-strings-to-dotnet-data-types.md - name: Convert .NET Framework Types to Strings href: ../../standard/data/xml/converting-dotnet-types-to-strings.md - - name: Supplemental API remarks - items: - - name: System.Xml.Schema.XmlSchemaSet class - href: ../../fundamentals/runtime-libraries/system-xml-schema-xmlschemaset.md - - name: System.Xml.Serialization.CodeGenerationOptions class - href: ../../fundamentals/runtime-libraries/system-xml-serialization-codegenerationoptions.md - - name: System.Xml.Serialization.XmlSerializer class - href: ../../fundamentals/runtime-libraries/system-xml-serialization-xmlserializer.md - - name: System.Xml.XmlConvert class - href: ../../fundamentals/runtime-libraries/system-xml-xmlconvert.md - - name: System.Xml.XmlDocument class - href: ../../fundamentals/runtime-libraries/system-xml-xmldocument.md - - name: System.Xml.XmlReader class - items: - - name: Type remarks - href: ../../fundamentals/runtime-libraries/system-xml-xmlreader.md - displayName: xmlreader - - name: Create method - href: ../../fundamentals/runtime-libraries/system-xml-xmlreader-create.md - - name: System.Xml.XmlReaderSettings class - items: - - name: Type remarks - href: ../../fundamentals/runtime-libraries/system-xml-xmlreadersettings.md - displayName: xmlreadersettings - - name: DtdProcessing property - href: ../../fundamentals/runtime-libraries/system-xml-xmlreadersettings-dtdprocessing.md - - name: Schemas property - href: ../../fundamentals/runtime-libraries/system-xml-xmlreadersettings-schemas.md - - name: System.Xml.XmlResolver class - href: ../../fundamentals/runtime-libraries/system-xml-xmlresolver.md - - name: System.Xml.XmlSecureResolver class - href: ../../fundamentals/runtime-libraries/system-xml-xmlsecureresolver.md - - name: System.Xml.XmlTextReader class - href: ../../fundamentals/runtime-libraries/system-xml-xmltextreader.md - - name: System.Xml.XmlTextWriter class - href: ../../fundamentals/runtime-libraries/system-xml-xmltextwriter.md - - name: System.Xml.XmlWriter class - href: ../../fundamentals/runtime-libraries/system-xml-xmlwriter.md - - name: System.Xml.Xsl.XslCompiledTransform class - href: ../../fundamentals/runtime-libraries/system-xml-xsl-xslcompiledtransform.md - name: Microsoft.Data.Sqlite items: - name: Overview @@ -705,16 +659,6 @@ items: href: ../../standard/data/sqlite/dapper-limitations.md - name: System.Data.SQLite href: ../../standard/data/sqlite/compare.md - - name: Supplemental API remarks for System.Data types - items: - - name: CommandBehavior enum - href: ../../fundamentals/runtime-libraries/system-data-commandbehavior.md - - name: DataColumn.Expression property - href: ../../fundamentals/runtime-libraries/system-data-datacolumn-expression.md - - name: DataSet class - href: ../../fundamentals/runtime-libraries/system-data-dataset.md - - name: DataTable class - href: ../../fundamentals/runtime-libraries/system-data-datatable.md - name: Entity Framework Core href: /ef/core/ - name: Azure Storage diff --git a/docs/navigate/security/toc.yml b/docs/navigate/security/toc.yml index d9f49bf3be221..284ff9d988d41 100644 --- a/docs/navigate/security/toc.yml +++ b/docs/navigate/security/toc.yml @@ -73,14 +73,4 @@ items: href: ../../standard/security/security-and-on-the-fly-code-generation.md - name: Timing vulnerabilities with CBC-mode symmetric decryption using padding href: ../../standard/security/vulnerabilities-cbc-mode.md -- name: Supplemental API remarks - items: - - name: The RSACryptoServiceProvider class - href: ../../fundamentals/runtime-libraries/system-security-cryptography-rsacryptoserviceprovider.md - - name: The RSAParameters struct - href: ../../fundamentals/runtime-libraries/system-security-cryptography-rsaparameters.md - - name: The SecureString class - href: ../../fundamentals/runtime-libraries/system-security-securestring.md - - name: The SignedXml class - href: ../../fundamentals/runtime-libraries/system-security-cryptography-xml-signedxml.md diff --git a/docs/navigate/tools-diagnostics/toc.yml b/docs/navigate/tools-diagnostics/toc.yml index 0956f23e88898..98dd25a48b4bf 100644 --- a/docs/navigate/tools-diagnostics/toc.yml +++ b/docs/navigate/tools-diagnostics/toc.yml @@ -572,14 +572,6 @@ items: items: - name: Get started href: ../../core/diagnostics/diagnosticsource-diagnosticlistener.md - - name: Supplemental API remarks - items: - - name: The EventSource class - href: ../../fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md - - name: The EventWrittenEventArgs class - href: ../../fundamentals/runtime-libraries/system-diagnostics-tracing-eventwritteneventargs.md - - name: The PerformanceCounterType enum - href: ../../fundamentals/runtime-libraries/system-diagnostics-performancecountertype.md - name: .NET CLI global tools items: - name: Overview From 9827fb98639773ad377880840c2b5fc3431743f2 Mon Sep 17 00:00:00 2001 From: Genevieve Warren <24882762+gewarren@users.noreply.github.com> Date: Tue, 16 Jun 2026 10:49:23 -0700 Subject: [PATCH 2/6] remarks files --- .../system-accessviolationexception.md | 36 -- .../runtime-libraries/system-appcontext.md | 129 ----- .../system-appdomain-unhandledexception.md | 35 -- .../runtime-libraries/system-boolean.md | 156 ------ .../runtime-libraries/system-byte.md | 84 ---- .../runtime-libraries/system-char.md | 97 ---- .../system-collections-generic-hashset{t}.md | 58 --- .../system-collections-generic-list{t}.md | 70 --- ...yedcollection{tkey,titem}-changeitemkey.md | 22 - ...ons-objectmodel-observablecollection{t}.md | 35 -- .../runtime-libraries/system-console.md | 145 ------ .../runtime-libraries/system-convert.md | 120 ----- .../system-data-commandbehavior.md | 23 - .../system-data-datacolumn-expression.md | 298 ------------ .../runtime-libraries/system-data-dataset.md | 38 -- .../system-data-datatable.md | 44 -- .../system-datetime-tobinary.md | 35 -- .../system-datetime-tryparse.md | 49 -- .../runtime-libraries/system-datetime.md | 402 --------------- .../runtime-libraries/system-decimal.md | 56 --- .../system-delegate-createdelegate.md | 121 ----- ...stem-diagnostics-performancecountertype.md | 140 ------ ...ostics-processstartinfo-useshellexecute.md | 28 -- .../system-diagnostics-tracing-eventsource.md | 74 --- ...agnostics-tracing-eventwritteneventargs.md | 26 - .../system-double-compareto.md | 48 -- .../system-double-epsilon.md | 37 -- .../runtime-libraries/system-double-equals.md | 54 --- .../runtime-libraries/system-double.md | 214 -------- .../system-drawing-drawing2d-matrix.md | 51 -- .../system-dynamic-expandoobject.md | 133 ----- .../runtime-libraries/system-enum.md | 195 -------- ...stem-environment-getenvironmentvariable.md | 61 --- .../system-exception-data.md | 32 -- .../system-exception-message.md | 27 -- .../runtime-libraries/system-exception.md | 230 --------- .../system-flagsattribute.md | 60 --- .../runtime-libraries/system-gc.md | 44 -- .../system-globalization-compareinfo.md | 34 -- .../system-globalization-compareoptions.md | 22 - ...zation-cultureandregioninfobuilder-ctor.md | 32 -- ...obalization-cultureandregioninfobuilder.md | 66 --- ...lobalization-cultureinfo-currentculture.md | 87 ---- ...balization-cultureinfo-currentuiculture.md | 71 --- ...balization-cultureinfo-invariantculture.md | 34 -- .../system-globalization-cultureinfo.md | 227 --------- ...system-globalization-datetimeformatinfo.md | 282 ----------- .../system-globalization-numberformatinfo.md | 234 --------- .../system-globalization-persiancalendar.md | 36 -- .../system-globalization-regioninfo.md | 38 -- .../system-globalization-sortkey.md | 46 -- .../system-globalization-sortversion.md | 51 -- .../system-iasyncdisposable.md | 27 -- .../runtime-libraries/system-idisposable.md | 98 ---- .../runtime-libraries/system-int32.md | 76 --- .../runtime-libraries/system-int64.md | 76 --- .../system-invalidcastexception.md | 108 ----- .../system-invalidoperationexception.md | 256 ---------- .../runtime-libraries/system-io-filestream.md | 36 -- .../system-io-filesystemwatcher.md | 51 -- ...ystem-linq-expressions-binaryexpression.md | 73 --- .../system-linq-expressions-expression-add.md | 34 -- .../system-midpointrounding.md | 59 --- .../system-net-ftpwebrequest-proxy.md | 19 - .../system-net-http-httpclient.md | 144 ------ .../system-net-http-httpclienthandler.md | 14 - .../system-net-httplistener.md | 52 -- .../system-net-sockets-socket.md | 28 -- .../system-notimplementedexception.md | 33 -- .../system-notsupportedexception.md | 97 ---- .../runtime-libraries/system-nullable.md | 22 - .../runtime-libraries/system-nullable{t}.md | 32 -- .../system-numerics-biginteger.md | 126 ----- .../system-numerics-complex.md | 100 ---- .../runtime-libraries/system-object-equals.md | 155 ------ .../system-object-finalize.md | 81 ---- .../system-object-gethashcode.md | 77 --- .../system-object-tostring.md | 154 ------ .../runtime-libraries/system-object.md | 28 -- .../runtime-libraries/system-random.md | 242 --------- ...lection-context-customreflectioncontext.md | 33 -- .../system-reflection-emit-assemblybuilder.md | 94 ---- .../system-reflection-emit-dynamicilinfo.md | 20 - ...ction-emit-dynamicmethod-createdelegate.md | 56 --- ...stem-reflection-emit-dynamicmethod-ctor.md | 84 ---- ...ction-emit-dynamicmethod-getilgenerator.md | 40 -- ...em-reflection-emit-dynamicmethod-invoke.md | 34 -- ...n-emit-dynamicmethod-issecuritycritical.md | 44 -- .../system-reflection-emit-dynamicmethod.md | 52 -- .../system-reflection-emit-methodbuilder.md | 43 -- ...eflection-emit-persistedassemblybuilder.md | 132 ----- .../system-reflection-emit-typebuilder.md | 42 -- ...tableexecutable-debugdirectoryentrytype.md | 27 -- ...ources-missingmanifestresourceexception.md | 49 -- ...urces-neutralresourceslanguageattribute.md | 118 ----- .../system-resources-resourcemanager-ctor.md | 123 ----- ...tem-resources-resourcemanager-getobject.md | 103 ---- ...tem-resources-resourcemanager-getstring.md | 106 ---- .../system-resources-resourcemanager.md | 308 ------------ .../system-resources-resourcereader.md | 111 ----- ...urces-satellitecontractversionattribute.md | 20 - ...lerservices-internalsvisibletoattribute.md | 62 --- ...ilerservices-runtimehelpers-gethashcode.md | 49 -- ...em-runtime-interopservices-comexception.md | 31 -- ...tem-runtime-interopservices-comwrappers.md | 57 --- ...untime-interopservices-icustommarshaler.md | 154 ------ ...interopservices-marshal-getactiveobject.md | 16 - ...stem-runtime-interopservices-safehandle.md | 39 -- ...stem-runtime-loader-assemblyloadcontext.md | 58 --- ...ime-serialization-datacontractattribute.md | 45 -- ...me-serialization-datacontractserializer.md | 49 -- ...ime-serialization-iextensibledataobject.md | 24 - ...e-serialization-xsddatacontractexporter.md | 33 -- ...versioning-componentguaranteesattribute.md | 132 ----- ...y-cryptography-rsacryptoserviceprovider.md | 22 - ...tem-security-cryptography-rsaparameters.md | 47 -- ...tem-security-cryptography-xml-signedxml.md | 148 ------ .../system-security-securestring.md | 112 ----- .../system-single-compareto.md | 46 -- .../system-single-epsilon.md | 37 -- .../runtime-libraries/system-single-equals.md | 49 -- .../runtime-libraries/system-single.md | 223 --------- .../runtime-libraries/system-span{t}.md | 61 --- .../runtime-libraries/system-string-ctor.md | 190 -------- .../runtime-libraries/system-string-format.md | 343 ------------- .../runtime-libraries/system-string-intern.md | 31 -- .../system-string-isnullorempty.md | 36 -- .../runtime-libraries/system-string.md | 459 ------------------ .../system-stringcomparer.md | 23 - .../system-text-encoding-default.md | 19 - .../runtime-libraries/system-text-encoding.md | 211 -------- ...tem-text-regularexpressions-regex-match.md | 46 -- .../system-text-regularexpressions-regex.md | 132 ----- .../runtime-libraries/system-text-rune.md | 199 -------- .../system-text-stringbuilder.md | 207 -------- .../system-threading-monitor-wait.md | 60 --- .../system-threading-monitor.md | 121 ----- .../system-threading-readerwriterlockslim.md | 137 ------ .../system-threading-tasks-task.md | 105 ---- .../system-threading-tasks-taskscheduler.md | 64 --- .../system-threading-thread.md | 166 ------- .../system-timespan-parse.md | 45 -- .../system-timespan-tryparse.md | 82 ---- .../runtime-libraries/system-timespan.md | 95 ---- .../system-type-getproperty.md | 83 ---- .../runtime-libraries/system-type-gettype.md | 136 ------ .../system-type-makegenerictype.md | 69 --- .../runtime-libraries/system-type.md | 84 ---- .../system-typeinitializationexception.md | 117 ----- .../runtime-libraries/system-uri.md | 155 ------ .../runtime-libraries/system-version.md | 93 ---- .../system-xml-linq-xname.md | 126 ----- .../system-xml-linq-xnamespace.md | 179 ------- .../system-xml-schema-xmlschemaset.md | 51 -- ...xml-serialization-codegenerationoptions.md | 23 - .../system-xml-serialization-xmlserializer.md | 201 -------- .../system-xml-xmlconvert.md | 44 -- .../system-xml-xmldocument.md | 214 -------- .../system-xml-xmlreader-create.md | 92 ---- .../runtime-libraries/system-xml-xmlreader.md | 291 ----------- ...tem-xml-xmlreadersettings-dtdprocessing.md | 25 - .../system-xml-xmlreadersettings-schemas.md | 25 - .../system-xml-xmlreadersettings.md | 34 -- .../system-xml-xmlresolver.md | 53 -- .../system-xml-xmlsecureresolver.md | 103 ---- .../system-xml-xmltextreader.md | 58 --- .../system-xml-xmltextwriter.md | 109 ----- .../runtime-libraries/system-xml-xmlwriter.md | 133 ----- .../system-xml-xsl-xslcompiledtransform.md | 30 -- 169 files changed, 15497 deletions(-) delete mode 100644 docs/fundamentals/runtime-libraries/system-accessviolationexception.md delete mode 100644 docs/fundamentals/runtime-libraries/system-appcontext.md delete mode 100644 docs/fundamentals/runtime-libraries/system-appdomain-unhandledexception.md delete mode 100644 docs/fundamentals/runtime-libraries/system-boolean.md delete mode 100644 docs/fundamentals/runtime-libraries/system-byte.md delete mode 100644 docs/fundamentals/runtime-libraries/system-char.md delete mode 100644 docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md delete mode 100644 docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md delete mode 100644 docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md delete mode 100644 docs/fundamentals/runtime-libraries/system-collections-objectmodel-observablecollection{t}.md delete mode 100644 docs/fundamentals/runtime-libraries/system-console.md delete mode 100644 docs/fundamentals/runtime-libraries/system-convert.md delete mode 100644 docs/fundamentals/runtime-libraries/system-data-commandbehavior.md delete mode 100644 docs/fundamentals/runtime-libraries/system-data-datacolumn-expression.md delete mode 100644 docs/fundamentals/runtime-libraries/system-data-dataset.md delete mode 100644 docs/fundamentals/runtime-libraries/system-data-datatable.md delete mode 100644 docs/fundamentals/runtime-libraries/system-datetime-tobinary.md delete mode 100644 docs/fundamentals/runtime-libraries/system-datetime-tryparse.md delete mode 100644 docs/fundamentals/runtime-libraries/system-datetime.md delete mode 100644 docs/fundamentals/runtime-libraries/system-decimal.md delete mode 100644 docs/fundamentals/runtime-libraries/system-delegate-createdelegate.md delete mode 100644 docs/fundamentals/runtime-libraries/system-diagnostics-performancecountertype.md delete mode 100644 docs/fundamentals/runtime-libraries/system-diagnostics-processstartinfo-useshellexecute.md delete mode 100644 docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md delete mode 100644 docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventwritteneventargs.md delete mode 100644 docs/fundamentals/runtime-libraries/system-double-compareto.md delete mode 100644 docs/fundamentals/runtime-libraries/system-double-epsilon.md delete mode 100644 docs/fundamentals/runtime-libraries/system-double-equals.md delete mode 100644 docs/fundamentals/runtime-libraries/system-double.md delete mode 100644 docs/fundamentals/runtime-libraries/system-drawing-drawing2d-matrix.md delete mode 100644 docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md delete mode 100644 docs/fundamentals/runtime-libraries/system-enum.md delete mode 100644 docs/fundamentals/runtime-libraries/system-environment-getenvironmentvariable.md delete mode 100644 docs/fundamentals/runtime-libraries/system-exception-data.md delete mode 100644 docs/fundamentals/runtime-libraries/system-exception-message.md delete mode 100644 docs/fundamentals/runtime-libraries/system-exception.md delete mode 100644 docs/fundamentals/runtime-libraries/system-flagsattribute.md delete mode 100644 docs/fundamentals/runtime-libraries/system-gc.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-compareoptions.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder-ctor.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentculture.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentuiculture.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-invariantculture.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-persiancalendar.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-regioninfo.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-sortkey.md delete mode 100644 docs/fundamentals/runtime-libraries/system-globalization-sortversion.md delete mode 100644 docs/fundamentals/runtime-libraries/system-iasyncdisposable.md delete mode 100644 docs/fundamentals/runtime-libraries/system-idisposable.md delete mode 100644 docs/fundamentals/runtime-libraries/system-int32.md delete mode 100644 docs/fundamentals/runtime-libraries/system-int64.md delete mode 100644 docs/fundamentals/runtime-libraries/system-invalidcastexception.md delete mode 100644 docs/fundamentals/runtime-libraries/system-invalidoperationexception.md delete mode 100644 docs/fundamentals/runtime-libraries/system-io-filestream.md delete mode 100644 docs/fundamentals/runtime-libraries/system-io-filesystemwatcher.md delete mode 100644 docs/fundamentals/runtime-libraries/system-linq-expressions-binaryexpression.md delete mode 100644 docs/fundamentals/runtime-libraries/system-linq-expressions-expression-add.md delete mode 100644 docs/fundamentals/runtime-libraries/system-midpointrounding.md delete mode 100644 docs/fundamentals/runtime-libraries/system-net-ftpwebrequest-proxy.md delete mode 100644 docs/fundamentals/runtime-libraries/system-net-http-httpclient.md delete mode 100644 docs/fundamentals/runtime-libraries/system-net-http-httpclienthandler.md delete mode 100644 docs/fundamentals/runtime-libraries/system-net-httplistener.md delete mode 100644 docs/fundamentals/runtime-libraries/system-net-sockets-socket.md delete mode 100644 docs/fundamentals/runtime-libraries/system-notimplementedexception.md delete mode 100644 docs/fundamentals/runtime-libraries/system-notsupportedexception.md delete mode 100644 docs/fundamentals/runtime-libraries/system-nullable.md delete mode 100644 docs/fundamentals/runtime-libraries/system-nullable{t}.md delete mode 100644 docs/fundamentals/runtime-libraries/system-numerics-biginteger.md delete mode 100644 docs/fundamentals/runtime-libraries/system-numerics-complex.md delete mode 100644 docs/fundamentals/runtime-libraries/system-object-equals.md delete mode 100644 docs/fundamentals/runtime-libraries/system-object-finalize.md delete mode 100644 docs/fundamentals/runtime-libraries/system-object-gethashcode.md delete mode 100644 docs/fundamentals/runtime-libraries/system-object-tostring.md delete mode 100644 docs/fundamentals/runtime-libraries/system-object.md delete mode 100644 docs/fundamentals/runtime-libraries/system-random.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-context-customreflectioncontext.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-assemblybuilder.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicilinfo.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-methodbuilder.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-persistedassemblybuilder.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-emit-typebuilder.md delete mode 100644 docs/fundamentals/runtime-libraries/system-reflection-portableexecutable-debugdirectoryentrytype.md delete mode 100644 docs/fundamentals/runtime-libraries/system-resources-missingmanifestresourceexception.md delete mode 100644 docs/fundamentals/runtime-libraries/system-resources-neutralresourceslanguageattribute.md delete mode 100644 docs/fundamentals/runtime-libraries/system-resources-resourcemanager-ctor.md delete mode 100644 docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getobject.md delete mode 100644 docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getstring.md delete mode 100644 docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md delete mode 100644 docs/fundamentals/runtime-libraries/system-resources-resourcereader.md delete mode 100644 docs/fundamentals/runtime-libraries/system-resources-satellitecontractversionattribute.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-compilerservices-internalsvisibletoattribute.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-compilerservices-runtimehelpers-gethashcode.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-interopservices-comexception.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-interopservices-comwrappers.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-interopservices-icustommarshaler.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-interopservices-marshal-getactiveobject.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-interopservices-safehandle.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-loader-assemblyloadcontext.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractattribute.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractserializer.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-serialization-iextensibledataobject.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-serialization-xsddatacontractexporter.md delete mode 100644 docs/fundamentals/runtime-libraries/system-runtime-versioning-componentguaranteesattribute.md delete mode 100644 docs/fundamentals/runtime-libraries/system-security-cryptography-rsacryptoserviceprovider.md delete mode 100644 docs/fundamentals/runtime-libraries/system-security-cryptography-rsaparameters.md delete mode 100644 docs/fundamentals/runtime-libraries/system-security-cryptography-xml-signedxml.md delete mode 100644 docs/fundamentals/runtime-libraries/system-security-securestring.md delete mode 100644 docs/fundamentals/runtime-libraries/system-single-compareto.md delete mode 100644 docs/fundamentals/runtime-libraries/system-single-epsilon.md delete mode 100644 docs/fundamentals/runtime-libraries/system-single-equals.md delete mode 100644 docs/fundamentals/runtime-libraries/system-single.md delete mode 100644 docs/fundamentals/runtime-libraries/system-span{t}.md delete mode 100644 docs/fundamentals/runtime-libraries/system-string-ctor.md delete mode 100644 docs/fundamentals/runtime-libraries/system-string-format.md delete mode 100644 docs/fundamentals/runtime-libraries/system-string-intern.md delete mode 100644 docs/fundamentals/runtime-libraries/system-string-isnullorempty.md delete mode 100644 docs/fundamentals/runtime-libraries/system-string.md delete mode 100644 docs/fundamentals/runtime-libraries/system-stringcomparer.md delete mode 100644 docs/fundamentals/runtime-libraries/system-text-encoding-default.md delete mode 100644 docs/fundamentals/runtime-libraries/system-text-encoding.md delete mode 100644 docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex-match.md delete mode 100644 docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex.md delete mode 100644 docs/fundamentals/runtime-libraries/system-text-rune.md delete mode 100644 docs/fundamentals/runtime-libraries/system-text-stringbuilder.md delete mode 100644 docs/fundamentals/runtime-libraries/system-threading-monitor-wait.md delete mode 100644 docs/fundamentals/runtime-libraries/system-threading-monitor.md delete mode 100644 docs/fundamentals/runtime-libraries/system-threading-readerwriterlockslim.md delete mode 100644 docs/fundamentals/runtime-libraries/system-threading-tasks-task.md delete mode 100644 docs/fundamentals/runtime-libraries/system-threading-tasks-taskscheduler.md delete mode 100644 docs/fundamentals/runtime-libraries/system-threading-thread.md delete mode 100644 docs/fundamentals/runtime-libraries/system-timespan-parse.md delete mode 100644 docs/fundamentals/runtime-libraries/system-timespan-tryparse.md delete mode 100644 docs/fundamentals/runtime-libraries/system-timespan.md delete mode 100644 docs/fundamentals/runtime-libraries/system-type-getproperty.md delete mode 100644 docs/fundamentals/runtime-libraries/system-type-gettype.md delete mode 100644 docs/fundamentals/runtime-libraries/system-type-makegenerictype.md delete mode 100644 docs/fundamentals/runtime-libraries/system-type.md delete mode 100644 docs/fundamentals/runtime-libraries/system-typeinitializationexception.md delete mode 100644 docs/fundamentals/runtime-libraries/system-uri.md delete mode 100644 docs/fundamentals/runtime-libraries/system-version.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-linq-xname.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-linq-xnamespace.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-schema-xmlschemaset.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-serialization-codegenerationoptions.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-serialization-xmlserializer.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmlconvert.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmldocument.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmlreader-create.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmlreader.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-dtdprocessing.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings-schemas.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmlreadersettings.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmlresolver.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmlsecureresolver.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmltextreader.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmltextwriter.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xmlwriter.md delete mode 100644 docs/fundamentals/runtime-libraries/system-xml-xsl-xslcompiledtransform.md diff --git a/docs/fundamentals/runtime-libraries/system-accessviolationexception.md b/docs/fundamentals/runtime-libraries/system-accessviolationexception.md deleted file mode 100644 index 3883e2df177c9..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-accessviolationexception.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: System.AccessViolationException class -description: Learn about the System.AccessViolationException class. -ms.date: 05/28/2025 ---- -# System.AccessViolationException class - -[!INCLUDE [context](includes/context.md)] - -An access violation occurs in unmanaged or unsafe code when the code attempts to read or write to memory that has not been allocated, or to which it does not have access. This usually occurs because a pointer has a bad value. Not all reads or writes through bad pointers lead to access violations, so an access violation usually indicates that several reads or writes have occurred through bad pointers, and that memory might be corrupted. Thus, access violations almost always indicate serious programming errors. An clearly identifies these serious errors. - -In programs that consist entirely of verifiable managed code, all references are either valid or null, and access violations are impossible. Any operation that attempts to reference a null reference in verifiable code throws a exception. An occurs only when verifiable managed code interacts with unmanaged code or with unsafe managed code. - -## Troubleshoot AccessViolationException exceptions - -An exception can occur only in unsafe managed code or when verifiable managed code interacts with unmanaged code: - -- An access violation that occurs in unsafe managed code can be expressed as either a exception or an exception, depending on the platform. -- An access violation in unmanaged code that bubbles up to managed code is always wrapped in an exception. - -In either case, you can identify and correct the cause of the exception as follows: - -- Make sure that the memory that you're attempting to access has been allocated. An exception is always thrown by an attempt to access protected memory—that is, to access memory that's not allocated or that's not owned by a process. - - Automatic memory management is one of the services that the .NET runtime provides. If managed code provides the same functionality as your unmanaged code, consider moving to managed code to take advantage of this functionality. For more information, see [Automatic memory management](../../standard/automatic-memory-management.md). - -- Make sure that the memory that you're attempting to access hasn't been corrupted. If several read or write operations have occurred through bad pointers, memory might be corrupted. This typically occurs when reading or writing to addresses outside of a predefined buffer. - -## AccessViolationException and try/catch blocks - - exceptions thrown by the .NET runtime aren't handled by the `catch` statement in a structured exception handler if the exception occurs outside of the memory reserved by the runtime. - -**.NET Framework only**: To handle such an exception, apply the attribute to the method in which the exception is thrown. This change does not affect exceptions thrown by user code, which can continue to be caught by a `catch` statement. - -> [!CAUTION] -> The [HandleProcessCorruptedStateExceptions attribute](xref:System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptionsAttribute) is obsolete in current .NET versions. Recovery from corrupted process state–exceptions isn't supported, and the attribute, if present, is ignored. diff --git a/docs/fundamentals/runtime-libraries/system-appcontext.md b/docs/fundamentals/runtime-libraries/system-appcontext.md deleted file mode 100644 index d76b16b288eef..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-appcontext.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: System.AppContext class -description: Learn about the System.AppContext class through these additional API remarks. -ms.date: 01/02/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.AppContext class - -[!INCLUDE [context](includes/context.md)] - -The class enables library writers to provide a uniform opt-out mechanism for new functionality for their users. It establishes a loosely coupled contract between components in order to communicate an opt-out request. This capability is typically important when a change is made to existing functionality. Conversely, there is already an implicit opt-in for new functionality. - -## AppContext for library developers - -Libraries use the class to define and expose compatibility switches, while library users can set those switches to affect the library behavior. By default, libraries provide the new functionality, and they only alter it (that is, they provide the previous functionality) if the switch is set. This allows libraries to provide new behavior for an existing API while continuing to support callers who depend on the previous behavior. - -### Define the switch name - -The most common way to allow consumers of your library to opt out of a change of behavior is to define a named switch. Its `value` element is a name/value pair that consists of the name of a switch and its value. By default, the switch is always implicitly `false`, which provides the new behavior (and makes the new behavior opt-in by default). Setting the switch to `true` enables it, which provides the legacy behavior. Explicitly setting the switch to `false` also provides the new behavior. - -It's beneficial to use a consistent format for switch names, since they're a formal contract exposed by a library. The following are two obvious formats: - -- *Switch*.*namespace*.*switchname* -- *Switch*.*library*.*switchname* - -Once you define and document the switch, callers can use it by calling the method programmatically. .NET Framework apps can also use the switch by adding an [``](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) element to their application configuration file or by using the registry. For more information about how callers use and set the value of configuration switches, see the [AppContext for library consumers](#appcontext-for-library-consumers) section. - -In .NET Framework, when the common language runtime runs an application, it automatically reads the registry's compatibility settings and loads the application configuration file to populate the application's instance. Because the instance is populated either programmatically by the caller or by the runtime, .NET Framework apps don't have to take any action, such as calling the method, to configure the instance. - -### Check the setting - -You can check if a consumer has declared the value of the switch and act appropriately by calling the method. The method returns `true` if the `switchName` argument is found, and its `isEnabled` argument indicates the value of the switch. Otherwise, the method returns `false`. - -### Example - -The following example illustrates the use of the class to allow the customer to choose the original behavior of a library method. The following is version 1.0 of a library named `StringLibrary`. It defines a `SubstringStartsAt` method that performs an ordinal comparison to determine the starting index of a substring within a larger string. - -:::code language="csharp" source="./snippets/System/AppContext/Overview/csharp/V1/Example4.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/AppContext/Overview/fsharp/Example4.fs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/AppContext/Overview/vb/V1/Example4.vb" id="Snippet4"::: - -The following example then uses the library to find the starting index of the substring "archæ" in "The archaeologist". Because the method performs an ordinal comparison, the substring cannot be found. - -:::code language="csharp" source="./snippets/System/AppContext/Overview/csharp/V1/Example4.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/AppContext/Overview/fsharp/Example4.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/AppContext/Overview/vb/V1/Example4.vb" id="Snippet5"::: - -Version 2.0 of the library, however, changes the `SubstringStartsAt` method to use culture-sensitive comparison. - -:::code language="csharp" source="./snippets/System/AppContext/Overview/csharp/V2/Example6.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System/AppContext/Overview/fsharp/Example6.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System/AppContext/Overview/vb/V2/Example6.vb" id="Snippet6"::: - -When the app is recompiled to run against the new version of the library, it now reports that the substring "archæ" is found at index 4 in "The archaeologist". - -:::code language="csharp" source="./snippets/System/AppContext/Overview/csharp/V2/Example6.cs" id="Snippet7"::: -:::code language="fsharp" source="./snippets/System/AppContext/Overview/fsharp/Example6.fs" id="Snippet7"::: -:::code language="vb" source="./snippets/System/AppContext/Overview/vb/V2/Example6.vb" id="Snippet7"::: - -This change can be prevented from breaking the applications that depend on the original behavior by defining a switch. In this case, the switch is named `StringLibrary.DoNotUseCultureSensitiveComparison`. Its default value, `false`, indicates that the library should perform its version 2.0 culture-sensitive comparison. `true` indicates that the library should perform its version 1.0 ordinal comparison. A slight modification of the previous code allows the library consumer to set the switch to determine the kind of comparison the method performs. - -:::code language="csharp" source="./snippets/System/AppContext/Overview/csharp/V3/Example8.cs" id="Snippet8"::: -:::code language="fsharp" source="./snippets/System/AppContext/Overview/fsharp/Example8.fs" id="Snippet8"::: -:::code language="vb" source="./snippets/System/AppContext/Overview/vb/V3/Example8.vb" id="Snippet8"::: - -A .NET Framework application can then use the following configuration file to restore the version 1.0 behavior. - -```xml - - - - - -``` - -When the application is run with the configuration file present, it produces the following output: - -```output -'archæ' not found in 'The archaeologist' -``` - -## AppContext for library consumers - -If you're the consumer of a library, the class allows you to take advantage of a library or library method's opt-out mechanism for new functionality. Individual methods of the class library that you are calling define particular switches that enable or disable a new behavior. The value of the switch is a Boolean. If it is `false`, which is typically the default value, the new behavior is enabled; if it is `true`, the new behavior is disabled, and the member behaves as it did previously. - -You can set the value of a switch by calling the method in your code. The `switchName` argument defines the switch name, and the `isEnabled` property defines the value of the switch. Because is a static class, it is available on a per-application domain basis. Calling the has application scope; that is, it affects only the application. - -.NET Framework apps have additional ways to set the value of a switch: - -- By adding an `` element to the [``](../../framework/configure-apps/file-schema/runtime/runtime-element.md) section of the app.config file. The switch has a single attribute, `value`, whose value is a string that represents a key/value pair containing both the switch name and its value. - - To define multiple switches, separate each switch's key/value pair in the [``](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) element's `value` attribute with a semicolon. In that case, the `` element has the following format: - - ```xml - - ``` - - Using the `` element to define a configuration setting has application scope; that is, it affects only the application. - - > [!NOTE] - > For information on the switches defined by .NET Framework, see [`` element](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md). - -- By adding an entry to the registry. Add a new string value to the **HKLM\SOFTWARE\Microsoft\\.NETFramework\AppContext** subkey. Set the name of the entry to the name of the switch. Set its value to one of the following options: `True`, `true`, `False`, or `false`. If the runtime encounters any other value, it ignores the switch. - - On a 64-bit operating system, you must also add the same entry to the **HKLM\SOFTWARE\Wow6432Node\Microsoft\\.NETFramework\AppContext** subkey. - - Using the registry to define an switch has machine scope; that is, it affects every application running on the machine. - -For ASP.NET and ASP.NET Core applications, you set a switch by adding an [``](../../framework/configure-apps/file-schema/appsettings/add-element-for-appsettings.md) element to the [``](../../framework/configure-apps/file-schema/appsettings/index.md) section of the web.config file. For example: - -```xml - - - - -``` - -If you set the same switch in more than one way, the order of precedence for determining which setting overrides the others is: - -1. The programmatic setting. -2. The setting in the app.config file (for .NET Framework apps) or the web.config file (for ASP.NET Core apps). -3. The registry setting (for .NET Framework apps only). - -## See also - -- [AppContext switch](../../framework/configure-apps/file-schema/runtime/appcontextswitchoverrides-element.md) diff --git a/docs/fundamentals/runtime-libraries/system-appdomain-unhandledexception.md b/docs/fundamentals/runtime-libraries/system-appdomain-unhandledexception.md deleted file mode 100644 index a5f4fdde13ec1..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-appdomain-unhandledexception.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: System.AppDomain.UnhandledException event -description: Learn about the System.AppDomain.UnhandledException event. -ms.date: 01/24/2024 ---- -# System.AppDomain.UnhandledException event - -[!INCLUDE [context](includes/context.md)] - -The event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. If sufficient information about the state of the application is available, other actions may be undertaken - such as saving program data for later recovery. Caution is advised, because program data can become corrupted when exceptions are not handled. The handler will also be running while holding locks held when the exception was thrown, so care should be taken to avoid waiting on other resources which could introduce deadlocks. - -This event can be handled in any application domain. However, the event is not necessarily raised in the application domain where the exception occurred. An exception is unhandled only if the entire stack for the thread has been unwound without finding an applicable exception handler, so the first place the event can be raised is in the application domain where the thread originated. - -If the event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for , the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains. - -For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain. - -> [!NOTE] -> The common language runtime suspends thread aborts while event handlers for the event are executing. - -If the event handler has a attribute with the appropriate flags, the event handler is treated as a constrained execution region. - -Starting with .NET Framework 4, this event is not raised for exceptions that corrupt the state of the process, such as stack overflows or access violations, unless the event handler is security-critical and has the attribute. - -To register an event handler for this event, you must have the required permissions, or a is thrown. - -For more information about handling events, see [Handling and Raising Events](../../standard/events/index.md). - -## Other events for unhandled exceptions - -For certain application models, the event can be preempted by other events if the unhandled exception occurs in the main application thread. - -In applications that use Windows Forms, unhandled exceptions in the main application thread cause the event to be raised. If this event is handled, the default behavior is that the unhandled exception does not terminate the application, although the application is left in an unknown state. In that case, the event is not raised. This behavior can be changed by using the application configuration file, or by using the method to change the mode to before the event handler is hooked up. This applies only to the main application thread. The event is raised for unhandled exceptions thrown in other threads. - -The Visual Basic application framework provides another event for unhandled exceptions in the main application thread—the event. This event has an event arguments object with the same name as the event arguments object used by , but with different properties. In particular, this event arguments object has an property that allows the application to continue running, ignoring the unhandled exception (and leaving the application in an unknown state). In that case, the event is not raised. diff --git a/docs/fundamentals/runtime-libraries/system-boolean.md b/docs/fundamentals/runtime-libraries/system-boolean.md deleted file mode 100644 index e60ff362f75ee..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-boolean.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: System.Boolean struct -description: Learn about the System.Boolean struct through these additional API remarks. -ms.date: 01/02/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Boolean struct - -[!INCLUDE [context](includes/context.md)] - -A instance can have either of two values: `true` or `false`. - -The structure provides methods that support the following tasks: - -- Converting Boolean values to strings: -- Parsing strings to convert them to Boolean values: and -- Comparing values: and - -This article explains these tasks and other usage details. - -## Format Boolean values - -The string representation of a is either "True" for a `true` value or "False" for a `false` value. The string representation of a value is defined by the read-only and fields. - -You use the method to convert Boolean values to strings. The Boolean structure includes two overloads: the parameterless method and the method, which includes a parameter that controls formatting. However, because this parameter is ignored, the two overloads produce identical strings. The method does not support culture-sensitive formatting. - -The following example illustrates formatting with the method. Note that the C# and VB examples use the [composite formatting](../../standard/base-types/composite-formatting.md) feature, while the F# example uses [string interpolation](../../fsharp/language-reference/interpolated-strings.md). In both cases the method is called implicitly. - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/tostring1.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/tostring1.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/tostring1.vb" id="Snippet3"::: - -Because the structure can have only two values, it is easy to add custom formatting. For simple custom formatting in which other string literals are substituted for "True" and "False", you can use any conditional evaluation feature supported by your language, such as the [conditional operator](../../csharp/language-reference/operators/conditional-operator.md) in C# or the [If operator](../../visual-basic/language-reference/operators/if-operator.md) in Visual Basic. The following example uses this technique to format values as "Yes" and "No" rather than "True" and "False". - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/tostring2.cs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/tostring2.vb" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/tostring2.fs" id="Snippet4"::: - -For more complex custom formatting operations, including culture-sensitive formatting, you can call the method and provide an implementation. The following example implements the and interfaces to provide culture-sensitive Boolean strings for the English (United States), French (France), and Russian (Russia) cultures. - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/format3.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/format3.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/format3.vb" id="Snippet5"::: - -Optionally, you can use [resource files](/dotnet/framework/resources/) to define culture-specific Boolean strings. - -## Convert to and from Boolean values - -The structure implements the interface. As a result, you can use the class to perform conversions between a value and any other primitive type in .NET, or you can call the structure's explicit implementations. However, conversions between a and the following types are not supported, so the corresponding conversion methods throw an exception: - -- Conversion between and (the and methods). - -- Conversion between and (the and methods). - -All conversions from integral or floating-point numbers to Boolean values convert non-zero values to `true` and zero values to `false`. The following example illustrates this by calling selected overloads of the class. - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/conversion1.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/conversion1.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/conversion1.vb" id="Snippet6"::: - -When converting from Boolean to numeric values, the conversion methods of the class convert `true` to 1 and `false` to 0. However, Visual Basic conversion functions convert `true` to either 255 (for conversions to values) or -1 (for all other numeric conversions). The following example converts `true` to numeric values by using a method, and, in the case of the Visual Basic example, by using the Visual Basic language's own conversion operator. - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/conversion3.cs" id="Snippet8"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/conversion3.fs" id="Snippet8"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/conversion3.vb" id="Snippet8"::: - -For conversions from to string values, see the [Format Boolean values](#format-boolean-values) section. For conversions from strings to values, see the [Parse Boolean values](#parse-boolean-values) section. - -## Parse Boolean values - -The structure includes two static parsing methods, and , that convert a string to a Boolean value. The string representation of a Boolean value is defined by the case-insensitive equivalents of the values of the and fields, which are "True" and "False", respectively. In other words, the only strings that parse successfully are "True", "False", "true", "false", or some mixed-case equivalent. You cannot successfully parse numeric strings such as "0" or "1". Leading or trailing white-space characters are not considered when performing the string comparison. - -The following example uses the and methods to parse a number of strings. Note that only the case-insensitive equivalents of "True" and "False" can be successfully parsed. - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/parse2.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/parse2.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/parse2.vb" id="Snippet2"::: - -If you're programming in Visual Basic, you can use the `CBool` function to convert the string representation of a number to a Boolean value. "0" is converted to `false`, and the string representation of any non-zero value is converted to `true`. If you're not programming in Visual Basic, you must convert your numeric string to a number before converting it to a Boolean. The following example illustrates this by converting an array of integers to Boolean values. - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/parse3.cs" id="Snippet9"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/parse3.fs" id="Snippet9"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/parse3.vb" id="Snippet9"::: - -## Compare Boolean values - -Because Boolean values are either `true` or `false`, there is little reason to explicitly call the method, which indicates whether an instance is greater than, less than, or equal to a specified value. Typically, to compare two Boolean variables, you call the method or use your language's equality operator. - -However, when you want to compare a Boolean variable with the literal Boolean value `true` or `false`, it's not necessary to do an explicit comparison, because the result of evaluating a Boolean value is that Boolean value. For example, the following two expressions are equivalent, but the second is more compact. However, both techniques offer comparable performance. - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/operations1.cs" id="Snippet11"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/operations1.fs" id="Snippet11"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/operations1.vb" id="Snippet11"::: - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/operations1.cs" id="Snippet12"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/operations1.fs" id="Snippet12"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/operations1.vb" id="Snippet12"::: - -## Work with Booleans as binary values - -A Boolean value occupies one byte of memory, as the following example shows. The C# example must be compiled with the `/unsafe` switch. - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/size1.cs" id="Snippet14"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/size1.fs" id="Snippet14"::: - -The byte's low-order bit is used to represent its value. A value of 1 represents `true`; a value of 0 represents `false`. - -> [!TIP] -> You can use the structure to work with sets of Boolean values. - -You can convert a Boolean value to its binary representation by calling the method. The method returns a byte array with a single element. To restore a Boolean value from its binary representation, you can call the method. - -The following example calls the method to convert a Boolean value to its binary representation and displays the individual bits of the value, and then calls the method to restore the value from its binary representation. - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/binary1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/binary1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/binary1.vb" id="Snippet1"::: - -## Perform operations with Boolean values - -This section illustrates how Boolean values are used in apps. The first section discusses its use as a flag. The second illustrates its use for arithmetic operations. - -### Boolean values as flags - -Boolean variables are most commonly used as flags, to signal the presence or absence of some condition. For example, in the method, the final parameter, `ignoreCase`, is a flag that indicates whether the comparison of two strings is case-insensitive (`ignoreCase` is `true`) or case-sensitive (`ignoreCase` is `false`). The value of the flag can then be evaluated in a conditional statement. - -The following example uses a simple console app to illustrate the use of Boolean variables as flags. The app accepts command-line parameters that enable output to be redirected to a specified file (the `/f` switch), and that enable output to be sent both to a specified file and to the console (the `/b` switch). The app defines a flag named `isRedirected` to indicate whether output is to be sent to a file, and a flag named `isBoth` to indicate that output should be sent to the console. The F# example uses a [recursive function](../../fsharp/language-reference/functions/recursive-functions-the-rec-keyword.md) to parse the arguments. - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/operations1.cs" id="Snippet10"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/operations1.fs" id="Snippet10"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/operations1.vb" id="Snippet10"::: - -### Booleans and arithmetic operations - -A Boolean value is sometimes used to indicate the presence of a condition that triggers a mathematical calculation. For example, a `hasShippingCharge` variable might serve as a flag to indicate whether to add shipping charges to an invoice amount. - -Because an operation with a `false` value has no effect on the result of an operation, it's not necessary to convert the Boolean to an integral value to use in the mathematical operation. Instead, you can use conditional logic. - -The following example computes an amount that consists of a subtotal, a shipping charge, and an optional service charge. The `hasServiceCharge` variable determines whether the service charge is applied. Instead of converting `hasServiceCharge` to a numeric value and multiplying it by the amount of the service charge, the example uses conditional logic to add the service charge amount if it is applicable. - -:::code language="csharp" source="./snippets/System/Boolean/Overview/csharp/operations2.cs" id="Snippet13"::: -:::code language="fsharp" source="./snippets/System/Boolean/Overview/fsharp/operations2.fs" id="Snippet13"::: -:::code language="vb" source="./snippets/System/Boolean/Overview/vb/operations2.vb" id="Snippet13"::: - -### Booleans and interop - -While marshaling base data types to COM is generally straightforward, the data type is an exception. You can apply the attribute to marshal the type to any of the following representations: - -|Enumeration type|Unmanaged format| -|----------------------|----------------------| -||A 4-byte integer value, where any nonzero value represents `true` and 0 represents `false`. This is the default format of a field in a structure and of a parameter in platform invoke calls.| -||A 1-byte integer value, where the 1 represents `true` and 0 represents `false`.| -||A 2-byte integer value, where -1 represents `true` and 0 represents `false`. This is the default format of a parameter in COM interop calls.| diff --git a/docs/fundamentals/runtime-libraries/system-byte.md b/docs/fundamentals/runtime-libraries/system-byte.md deleted file mode 100644 index 55d28327a0fed..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-byte.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: System.Byte struct -description: Learn about the System.Byte struct through these additional API remarks. -ms.date: 01/02/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Byte struct - -[!INCLUDE [context](includes/context.md)] - - is an immutable value type that represents unsigned integers with values that range from 0 (which is represented by the constant) to 255 (which is represented by the constant). .NET also includes a signed 8-bit integer value type, , which represents values that range from -128 to 127. - -## Instantiate a Byte value - -You can instantiate a value in several ways: - -- You can declare a variable and assign it a literal integer value that is within the range of the data type. The following example declares two variables and assigns them values in this way. - - :::code language="csharp" source="./snippets/System/Byte/Overview/csharp/byteinstantiation1.cs" id="Snippet1"::: - :::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/byteinstantiation1.fs" id="Snippet1"::: - :::code language="vb" source="./snippets/System/Byte/Overview/vb/byteinstantiate1.vb" id="Snippet1"::: - -- You can assign a non-byte numeric value to a byte. This is a narrowing conversion, so it requires a cast operator in C# and F#, or a conversion method in Visual Basic if `Option Strict` is on. If the non-byte value is a , , or value that includes a fractional component, the handling of its fractional part depends on the compiler performing the conversion. The following example assigns several numeric values to variables. - - :::code language="csharp" source="./snippets/System/Byte/Overview/csharp/byteinstantiation1.cs" id="Snippet2"::: - :::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/byteinstantiation1.fs" id="Snippet2"::: - :::code language="vb" source="./snippets/System/Byte/Overview/vb/byteinstantiate1.vb" id="Snippet2"::: - -- You can call a method of the class to convert any supported type to a value. This is possible because supports the interface. The following example illustrates the conversion of an array of values to values. - - :::code language="csharp" source="./snippets/System/Byte/Overview/csharp/tobyte1.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/tobyte1.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System/Convert/Overview/vb/tobyte1.vb" id="Snippet4"::: - -- You can call the or method to convert the string representation of a value to a . The string can contain either decimal or hexadecimal digits. The following example illustrates the parse operation by using both a decimal and a hexadecimal string. - - :::code language="csharp" source="./snippets/System/Byte/Overview/csharp/byteinstantiation1.cs" id="Snippet3"::: - :::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/byteinstantiation1.fs" id="Snippet3"::: - :::code language="vb" source="./snippets/System/Byte/Overview/vb/byteinstantiate1.vb" id="Snippet3"::: - -## Perform operations on Byte values - -The type supports standard mathematical operations such as addition, subtraction, division, multiplication, subtraction, negation, and unary negation. Like the other integral types, the type also supports the bitwise `AND`, `OR`, `XOR`, left shift, and right shift operators. - -You can use the standard numeric operators to compare two values, or you can call the or method. - -You can also call the members of the class to perform a wide range of numeric operations, including getting the absolute value of a number, calculating the quotient and remainder from integral division, determining the maximum or minimum value of two integers, getting the sign of a number, and rounding a number. - -## Represent a Byte as a String - -The type provides full support for standard and custom numeric format strings. (For more information, see [Formatting Types](../../standard/base-types/formatting-types.md), [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md), and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md).) However, most commonly, byte values are represented as one-digit to three-digit values without any additional formatting, or as two-digit hexadecimal values. - -To format a value as an integral string with no leading zeros, you can call the parameterless method. By using the "D" format specifier, you can also include a specified number of leading zeros in the string representation. By using the "X" format specifier, you can represent a value as a hexadecimal string. The following example formats the elements in an array of values in these three ways. - -:::code language="csharp" source="./snippets/System/Byte/Overview/csharp/formatting1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/formatting1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Byte/Overview/vb/formatting1.vb" id="Snippet1"::: - -You can also format a value as a binary, octal, decimal, or hexadecimal string by calling the method and supplying the base as the method's second parameter. The following example calls this method to display the binary, octal, and hexadecimal representations of an array of byte values. - -:::code language="csharp" source="./snippets/System/Byte/Overview/csharp/formatting1.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/formatting1.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Byte/Overview/vb/formatting1.vb" id="Snippet2"::: - -## Work with non-decimal Byte values - -In addition to working with individual bytes as decimal values, you might want to perform bitwise operations with byte values, or work with byte arrays or with the binary or hexadecimal representations of byte values. For example, overloads of the method can convert each of the primitive data types to a byte array, and the method converts a value to a byte array. - - values are represented in 8 bits by their magnitude only, without a sign bit. This is important to keep in mind when you perform bitwise operations on values or when you work with individual bits. To perform a numeric, Boolean, or comparison operation on any two non-decimal values, both values must use the same representation. - -When an operation is performed on two values, the values share the same representation, so the result is accurate. This is illustrated in the following example, which masks the lowest-order bit of a value to ensure that it is even. - -:::code language="csharp" source="./snippets/System/Byte/Overview/csharp/bitwise1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/bitwise1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Byte/Overview/vb/bitwise1.vb" id="Snippet1"::: - -On the other hand, when you work with both unsigned and signed bits, bitwise operations are complicated by the fact that the values use sign-and-magnitude representation for positive values, and two's complement representation for negative values. In order to perform a meaningful bitwise operation, the values must be converted to two equivalent representations, and information about the sign bit must be preserved. The following example does this to mask out bits 2 and 4 of an array of 8-bit signed and unsigned values. - -:::code language="csharp" source="./snippets/System/Byte/Overview/csharp/bitwise2.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Byte/Overview/fsharp/bitwise2.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Byte/Overview/vb/bitwise2.vb" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-char.md b/docs/fundamentals/runtime-libraries/system-char.md deleted file mode 100644 index 7db917accb75e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-char.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: System.Char struct -description: Learn about the System.Char struct through these additional API remarks. -ms.date: 01/02/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Char struct - -[!INCLUDE [context](includes/context.md)] - -The structure represents Unicode code points by using UTF-16 encoding. The value of a object is its 16-bit numeric (ordinal) value. - -If you aren't familiar with Unicode, scalar values, code points, surrogate pairs, UTF-16, and the type, see [Introduction to character encoding in .NET](../../standard/base-types/character-encoding-introduction.md). - -This article examines the relationship between a object and a character and discuss some common tasks performed with instances. We recommend that you consider the type, introduced in .NET Core 3.0, as an alternative to for performing some of these tasks. - -## Char objects, Unicode characters, and strings - -A object is a sequential collection of structures that represents a string of text. Most Unicode characters can be represented by a single object, but a character that is encoded as a base character, surrogate pair, and/or combining character sequence is represented by multiple objects. For this reason, a structure in a object is not necessarily equivalent to a single Unicode character. - -Multiple 16-bit code units are used to represent single Unicode characters in the following cases: - -- Glyphs, which may consist of a single character or of a base character followed by one or more combining characters. For example, the character ä is represented by a object whose code unit is U+0061 followed by a object whose code unit is U+0308. (The character ä can also be defined by a single object that has a code unit of U+00E4.) The following example illustrates that the character ä consists of two objects. - - :::code language="csharp" source="./snippets/System/Char/Overview/csharp/grapheme1.cs" id="Snippet1"::: - :::code language="fsharp" source="./snippets/System/Char/Overview/fsharp/grapheme1.fs" id="Snippet1"::: - :::code language="vb" source="./snippets/System/Char/Overview/vb/grapheme1.vb" id="Snippet1"::: - -- Characters outside the Unicode Basic Multilingual Plane (BMP). Unicode supports sixteen planes in addition to the BMP, which represents plane 0. A Unicode code point is represented in UTF-32 by a 21-bit value that includes the plane. For example, U+1D160 represents the MUSICAL SYMBOL EIGHTH NOTE character. Because UTF-16 encoding has only 16 bits, characters outside the BMP are represented by surrogate pairs in UTF-16. The following example illustrates that the UTF-32 equivalent of U+1D160, the MUSICAL SYMBOL EIGHTH NOTE character, is U+D834 U+DD60. U+D834 is the high surrogate; high surrogates range from U+D800 through U+DBFF. U+DD60 is the low surrogate; low surrogates range from U+DC00 through U+DFFF. - - :::code language="csharp" source="./snippets/System/Char/Overview/csharp/surrogate1.cs" id="Snippet2"::: - :::code language="fsharp" source="./snippets/System/Char/Overview/fsharp/surrogate1.fs" id="Snippet2"::: - :::code language="vb" source="./snippets/System/Char/Overview/vb/surrogate1.vb" id="Snippet2"::: - -## Characters and character categories - -Each Unicode character or valid surrogate pair belongs to a Unicode category. In .NET, Unicode categories are represented by members of the enumeration and include values such as , , and , for example. - -To determine the Unicode category of a character, call the method. For example, the following example calls the to display the Unicode category of each character in a string. The example works correctly only if there are no surrogate pairs in the instance. - -:::code language="csharp" source="./snippets/System/Char/Overview/csharp/GetUnicodeCategory3.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System/Char/Overview/fsharp/GetUnicodeCategory3.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System/Char/Overview/vb/GetUnicodeCategory3.vb" id="Snippet6"::: - -Internally, for characters outside the ASCII range (U+0000 through U+00FF), the method depends on Unicode categories reported by the class. Starting with .NET Framework 4.6.2, Unicode characters are classified based on [The Unicode Standard, Version 8.0.0](https://www.unicode.org/versions/Unicode8.0.0/). In versions of .NET Framework from .NET Framework 4 to .NET Framework 4.6.1, they are classified based on [The Unicode Standard, Version 6.3.0](https://www.unicode.org/versions/Unicode6.3.0/). - -## Characters and text elements - -Because a single character can be represented by multiple objects, it is not always meaningful to work with individual objects. For instance, the following example converts the Unicode code points that represent the Aegean numbers zero through 9 to UTF-16 encoded code units. Because it erroneously equates objects with characters, it inaccurately reports that the resulting string has 20 characters. - -:::code language="csharp" source="./snippets/System/Char/Overview/csharp/textelements2.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/Char/Overview/fsharp/textelements2.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/Char/Overview/vb/textelements2.vb" id="Snippet3"::: - -You can do the following to avoid the assumption that a object represents a single character: - -- You can work with a object in its entirety instead of working with its individual characters to represent and analyze linguistic content. - -- You can use as shown in the following example: - - :::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/CountLettersInString.cs" id="SnippetGoodExample"::: - :::code language="fsharp" source="./snippets/System.Text/Rune/Overview/fsharp/CountLettersInString.fs" id="SnippetGoodExample"::: - -- You can use the class to work with text elements instead of individual objects. The following example uses the object to count the number of text elements in a string that consists of the Aegean numbers zero through nine. Because it considers a surrogate pair a single character, it correctly reports that the string contains ten characters. - - :::code language="csharp" source="./snippets/System/Char/Overview/csharp/textelements2a.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System/Char/Overview/fsharp/textelements2a.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System/Char/Overview/vb/textelements2a.vb" id="Snippet4"::: - -- If a string contains a base character that has one or more combining characters, you can call the method to convert the substring to a single UTF-16 encoded code unit. The following example calls the method to convert the base character U+0061 (LATIN SMALL LETTER A) and combining character U+0308 (COMBINING DIAERESIS) to U+00E4 (LATIN SMALL LETTER A WITH DIAERESIS). - - :::code language="csharp" source="./snippets/System/Char/Overview/csharp/normalized.cs" id="Snippet5"::: - :::code language="fsharp" source="./snippets/System/Char/Overview/fsharp/normalized.fs" id="Snippet5"::: - :::code language="vb" source="./snippets/System/Char/Overview/vb/normalized.vb" id="Snippet5"::: - -## Common operations - -The structure provides methods to compare objects, convert the value of the current object to an object of another type, and determine the Unicode category of a object: - -|To do this|Use these `System.Char` methods| -|----------------|-------------------------------------| -|Compare objects| and | -|Convert a code point to a string|

See also the type.| -|Convert a object or a surrogate pair of objects to a code point|For a single character:

For a surrogate pair or a character in a string:

See also the type.| -|Get the Unicode category of a character|

See also .| -|Determine whether a character is in a particular Unicode category such as digit, letter, punctuation, control character, and so on|, , , , , , , , , , , , , , and

See also corresponding methods on the type.| -|Convert a object that represents a number to a numeric value type|

See also .| -|Convert a character in a string into a object| and | -|Convert a object to a object|| -|Change the case of a object|, , , and

See also corresponding methods on the type.| - -## Char values and interop - -When a managed type, which is represented as a Unicode UTF-16 encoded code unit, is passed to unmanaged code, the interop marshaller converts the character set to ANSI by default. You can apply the attribute to platform invoke declarations and the attribute to a COM interop declaration to control which character set a marshaled type uses. diff --git a/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md b/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md deleted file mode 100644 index cc8c9a4618871..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-collections-generic-hashset{t}.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: System.Collections.Generic.HashSet\ class -description: Learn about the System.Collections.Generic.HashSet\ class through these additional API remarks. -ms.date: 01/02/2024 -dev_langs: - - CSharp - - VB ---- -# System.Collections.Generic.HashSet\ class - -[!INCLUDE [context](includes/context.md)] - -The class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order. - -The capacity of a object is the number of elements that the object can hold. A object's capacity automatically increases as elements are added to the object. - -The class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the or collections. In simple terms, the class can be thought of as a collection without values. - -A collection is not sorted and cannot contain duplicate elements. If order or element duplication is more important than performance for your application, consider using the class together with the method. - - provides many mathematical set operations, such as set addition (unions) and set subtraction. The following table lists the provided operations and their mathematical equivalents. - -|HashSet operation|Mathematical equivalent| -|-------------------------------|-----------------------------| -||Union or set addition| -||Intersection| -||Set subtraction| -||Symmetric difference| - -In addition to the listed set operations, the class also provides methods for determining set equality, overlap of sets, and whether a set is a subset or superset of another set. - -**.NET Framework only:** For very large objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the `enabled` attribute of the [``](../../framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md) configuration element to `true` in the runtime environment. - -The class implements the interface. - -## HashSet and LINQ set operations - -LINQ provides access to the `Distinct`, `Union`, `Intersect`, and `Except` set operations on any data source that implements the or interfaces. provides a larger and more robust collection of set operations. For example, provides comparisons such as and . - -The primary difference between LINQ set operations and operations is that LINQ set operations always return a new collection, whereas the equivalent methods modify the current collection. - -Typically, if you must create a new set or if your application needs access only to the provided set operations, using LINQ set operations on any collection or array will be sufficient. However, if your application requires access to additional set operations, or if it is not desirable or necessary to create a new collection, use the class. - -The following table shows the operations and their equivalent LINQ set operations. - -|HashSet operation|LINQ equivalent| -|-------------------------------|---------------------| -||| -||| -||| -|Not provided.|| -||Not provided.| -||Not provided.| -||Not provided.| -||Not provided.| -||Not provided.| -||Not provided.| -||Not provided.| diff --git a/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md b/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md deleted file mode 100644 index 409cfee48c557..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-collections-generic-list{t}.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: System.Collections.Generic.List\ class -description: Learn about the System.Collections.Generic.List\ class through these additional API remarks. -ms.date: 01/02/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Collections.Generic.List\ class - -[!INCLUDE [context](includes/context.md)] - -The class is the generic equivalent of the class. It implements the generic interface by using an array whose size is dynamically increased as required. - -You can add items to a by using the or methods. - -The class uses both an equality comparer and an ordering comparer. - -- Methods such as , , , and use an equality comparer for the list elements. The default equality comparer for type `T` is determined as follows. If type `T` implements the generic interface, then the equality comparer is the method of that interface; otherwise, the default equality comparer is . - -- Methods such as and use an ordering comparer for the list elements. The default comparer for type `T` is determined as follows. If type `T` implements the generic interface, then the default comparer is the method of that interface; otherwise, if type `T` implements the nongeneric interface, then the default comparer is the method of that interface. If type `T` implements neither interface, then there is no default comparer, and a comparer or comparison delegate must be provided explicitly. - -The is not guaranteed to be sorted. You must sort the before performing operations (such as ) that require the to be sorted. - -Elements in this collection can be accessed using an integer index. Indexes in this collection are zero-based. - -**.NET Framework only:** For very large objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the `enabled` attribute of the [``](../../framework/configure-apps/file-schema/runtime/gcallowverylargeobjects-element.md) configuration element to `true` in the runtime environment. - - accepts `null` as a valid value for reference types and allows duplicate elements. - -For an immutable version of the class, see . - -## Performance considerations - -In deciding whether to use the or class, both of which have similar functionality, remember that the class performs better in most cases and is type safe. If a reference type is used for type `T` of the class, the behavior of the two classes is identical. However, if a value type is used for type `T`, you need to consider implementation and boxing issues. - -If a value type is used for type `T`, the compiler generates an implementation of the class specifically for that value type. That means a list element of a object does not have to be boxed before the element can be used, and after about 500 list elements are created, the memory saved by not boxing list elements is greater than the memory used to generate the class implementation. - -Make certain the value type used for type `T` implements the generic interface. If not, methods such as must call the method, which boxes the affected list element. If the value type implements the interface and you own the source code, also implement the generic interface to prevent the and methods from boxing list elements. If you do not own the source code, pass an object to the and methods. - -It's to your advantage to use the type-specific implementation of the class instead of using the class or writing a strongly typed wrapper collection yourself. That's because your implementation must do what .NET does for you already, and the .NET runtime can share common intermediate language code and metadata, which your implementation cannot. - -## F# considerations - -The class is used infrequently in F# code. Instead, [Lists](../../fsharp/language-reference/lists.md), which are immutable, singly-linked lists, are typically preferred. An F# `List` provides an ordered, immutable series of values, and is supported for use in functional-style development. When used from F#, the class is typically referred to by the `ResizeArray<'T>` type abbreviation to avoid naming conflicts with F# Lists. - -## Examples - -The following example demonstrates how to add, remove, and insert a simple business object in a . - -:::code language="csharp" source="./snippets/System.Collections.Generic/ListT/Overview/csharp/program.cs" id="snippet1"::: -:::code language="vb" source="./snippets/System.Collections.Generic/List/Overview/vb/module1.vb" id="snippet1"::: -:::code language="fsharp" source="./snippets/System.Collections.Generic/ListT/Overview/fsharp/addremoveinsert.fs" id="snippet1"::: - -The following example demonstrates several properties and methods of the generic class of type string. (For an example of a of complex types, see the method.) - -The parameterless constructor is used to create a list of strings with the default capacity. The property is displayed and then the method is used to add several items. The items are listed, and the property is displayed again, along with the property, to show that the capacity has been increased as needed. - -The method is used to test for the presence of an item in the list, the method is used to insert a new item in the middle of the list, and the contents of the list are displayed again. - -The default property (the indexer in C#) is used to retrieve an item, the method is used to remove the first instance of the duplicate item added earlier, and the contents are displayed again. The method always removes the first instance it encounters. - -The method is used to reduce the capacity to match the count, and the and properties are displayed. If the unused capacity had been less than 10 percent of total capacity, the list would not have been resized. - -Finally, the method is used to remove all items from the list, and the and properties are displayed. - -:::code language="csharp" source="./snippets/System.Collections.Generic/ListT/Overview/csharp/source.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Collections.Generic/List/Overview/vb/source.vb" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System.Collections.Generic/ListT/Overview/fsharp/listclass.fs" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md b/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md deleted file mode 100644 index bfed7c07babe6..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-collections-objectmodel-keyedcollection{tkey,titem}-changeitemkey.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: System.Collections.ObjectModel.KeyedCollection.ChangeItemKey method -description: Learn about the System.Collections.ObjectModel.KeyedCollection.ChangeItemKey method. -ms.date: 01/24/2024 ---- -# System.Collections.ObjectModel.KeyedCollection.ChangeItemKey method - -[!INCLUDE [context](includes/context.md)] - -The method does not modify the key embedded in `item`; it simply replaces the key saved in the lookup dictionary. Therefore, if `newKey` is different from the key that is embedded in `item`, you cannot access `item` by using the key returned by . - -This method does nothing if the does not have a lookup dictionary. - -Every key in a must be unique. A key cannot be `null`. - -This method is an O(1) operation. - -## Notes for implementers - -Before modifying the key embedded in an item, you must call this method to update the key in the lookup dictionary. If the dictionary creation threshold is -1, calling this method is not necessary. - -Do not expose the method as a public method of a derived class. Misuse of this method puts the lookup dictionary out of sync with item keys. For example, setting the key to `null` and then setting it to another value adds multiple keys for an item to the lookup dictionary. Expose this method internally to allow mutable item keys: When the key for an item changes, this method is used to change the key in the lookup dictionary. diff --git a/docs/fundamentals/runtime-libraries/system-collections-objectmodel-observablecollection{t}.md b/docs/fundamentals/runtime-libraries/system-collections-objectmodel-observablecollection{t}.md deleted file mode 100644 index cb036148c2182..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-collections-objectmodel-observablecollection{t}.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: System.Collections.ObjectModel.ObservableCollection\ class -description: Learn about the System.Collections.ObjectModel.ObservableCollection\ class through these additional API remarks. -ms.date: 01/02/2024 ---- -# System.Collections.ObjectModel.ObservableCollection\ class - -[!INCLUDE [context](includes/context.md)] - -The class represents a dynamic data collection that provides notifications when items get added or removed, or when the whole list is refreshed. - -In many cases, the data that you work with is a collection of objects. For example, a common scenario in data binding is to use an such as a , , or to display a collection of records. - -You can enumerate over any collection that implements the interface. However, to set up dynamic bindings so that insertions or deletions in the collection update the UI automatically, the collection must implement the interface. This interface exposes the event, an event that should be raised whenever the underlying collection changes. - -The class is a data collection type that implements the interface. - -Before implementing your own collection, consider using or one of the existing collection classes, such as , , and , among many others. If you have an advanced scenario and want to implement your own collection, consider using , which provides a non-generic collection of objects that can be individually accessed by index. Implementing provides the best performance with the data binding engine. - -> [!NOTE] -> To fully support transferring data values from binding source objects to binding targets, each object in your collection that supports bindable properties must implement an appropriate property changed notification mechanism such as the interface. - -For more information, see "Binding to Collections" in [Data Binding Overview](/dotnet/framework/wpf/data/data-binding-overview). - -## Notes on XAML usage - - can be used as a XAML object element in Windows Presentation Foundation (WPF), in versions 3.0 and 3.5. However, the usage has substantial limitations. - -- must be the root element, because the `x:TypeArguments` attribute that must be used to specify the constrained type of the generic is only supported on the object element for the root element. - -- You must declare an `x:Class` attribute (which entails that the build action for this XAML file must be `Page` or some other build action that compiles the XAML). - -- is in a namespace and assembly that are not initially mapped to the default XML namespace. You must map a prefix for the namespace and assembly, and then use that prefix on the object element tag for . - -A more straightforward way to use capabilities from XAML in an application is to declare your own non-generic custom collection class that derives from , and constrains it to a specific type. Then map the assembly that contains this class, and reference it as an object element in your XAML. diff --git a/docs/fundamentals/runtime-libraries/system-console.md b/docs/fundamentals/runtime-libraries/system-console.md deleted file mode 100644 index b44e1b2b98d4d..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-console.md +++ /dev/null @@ -1,145 +0,0 @@ ---- -title: System.Console class -description: Learn about the System.Console class through these additional API remarks. -ms.date: 01/02/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Console class - -[!INCLUDE [context](includes/context.md)] - -The console is an operating system window where users interact with the operating system or with a text-based console application by entering text input through the computer keyboard, and by reading text output from the computer terminal. For example, in the Windows operating system, the console is called the Command Prompt window and accepts MS-DOS commands. The class provides basic support for applications that read characters from, and write characters to, the console. - -## Console I/O streams - -When a console application starts, the operating system automatically associates three I/O streams with the console: standard input stream, standard output stream, and standard error output stream. Your application can read user input from the standard input stream; write normal data to the standard output stream; and write error data to the standard error output stream. These streams are presented to your application as the values of the , , and properties. - -By default, the value of the property is a object that represents the keyboard, and the values of the and properties are objects that represent a console window. However, you can set these properties to streams that do not represent the console window or keyboard; for example, you can set these properties to streams that represent files. To redirect the standard input, standard output, or standard error stream, call the , , or method, respectively. I/O operations that use these streams are synchronized, which means that multiple threads can read from, or write to, the streams. This means that methods that are ordinarily asynchronous, such as , execute synchronously if the object represents a console stream. - -> [!NOTE] -> Do not use the class to display output in unattended applications, such as server applications. Calls to methods such as and have no effect in GUI applications. - - class members that work normally when the underlying stream is directed to a console might throw an exception if the stream is redirected, for example, to a file. Program your application to catch exceptions if you redirect a standard stream. You can also use the , , and properties to determine whether a standard stream is redirected before performing an operation that throws an exception. - -It is sometimes useful to explicitly call the members of the stream objects represented by the , , and properties. For example, by default, the method reads input from the standard input stream. Similarly, the method writes data to the standard output stream, and the data is followed by the default line termination string, which can be found at . However, the class does not provide a corresponding method to write data to the standard error output stream, or a property to change the line termination string for data written to that stream. - -You can solve this problem by setting the property of the or property to another line termination string. For example, the following C# statement sets the line termination string for the standard error output stream to two carriage return and line feed sequences: - -`Console.Error.NewLine = "\r\n\r\n";` - -You can then explicitly call the method of the error output stream object, as in the following C# statement: - -`Console.Error.WriteLine();` - -## Screen buffer and console window - -Two closely related features of the console are the screen buffer and the console window. Text is actually read from or written to streams owned by the console, but appear to be read from or written to an area owned by the console called the screen buffer. The screen buffer is an attribute of the console, and is organized as a rectangular grid of rows and columns where each grid intersection, or character cell, can contain a character. Each character has its own foreground color, and each character cell has its own background color. - -The screen buffer is viewed through a rectangular region called the console window. The console window is another attribute of the console; it is not the console itself, which is an operating system window. The console window is arranged in rows and columns, is less than or equal to the size of the screen buffer, and can be moved to view different areas of the underlying screen buffer. If the screen buffer is larger than the console window, the console automatically displays scroll bars so the console window can be repositioned over the screen buffer area. - -A cursor indicates the screen buffer position where text is currently read or written. The cursor can be hidden or made visible, and its height can be changed. If the cursor is visible, the console window position is moved automatically so the cursor is always in view. - -The origin for character cell coordinates in the screen buffer is the upper left corner, and the positions of the cursor and the console window are measured relative to that origin. Use zero-based indexes to specify positions; that is, specify the topmost row as row 0, and the leftmost column as column 0. The maximum value for the row and column indexes is . - -## Unicode support for the console - -In general, the console reads input and writes output by using the current console code page, which the system locale defines by default. A code page can handle only a subset of available Unicode characters, so if you try to display characters that are not mapped by a particular code page, the console won't be able to display all characters or represent them accurately. The following example illustrates this problem. It tries to display the characters of the Cyrillic alphabet from U+0410 to U+044F to the console. If you run the example on a system that uses console code page 437, each character is replaced by a question mark (?), because Cyrillic characters do not map to the characters in code page 437. - -:::code language="csharp" source="./snippets/System/Console/Overview/csharp/unicode1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Console/Overview/vb/unicode1.vb" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Console/Overview/fsharp/unicode1.fs" id="Snippet1"::: - -In addition to supporting code pages, the class supports UTF-8 encoding with the class. Beginning with .NET Framework 4.5, the class also supports UTF-16 encoding with the class. To display Unicode characters to the console. you set the property to either or . - -Support for Unicode characters requires the encoder to recognize a particular Unicode character, and also requires a font that has the glyphs needed to render that character. To successfully display Unicode characters to the console, the console font must be set to a non-raster or TrueType font such as Consolas or Lucida Console. The following example shows how you can programmatically change the font from a raster font to Lucida Console. - -:::code language="csharp" source="./snippets/System/Console/Overview/csharp/setfont1.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/Console/Overview/vb/setfont1.vb" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/Console/Overview/fsharp/setfont1.fs" id="Snippet3"::: - -However, TrueType fonts can display only a subset of glyphs. For example, the Lucida Console font displays only 643 of the approximately 64,000 available characters from U+0021 to U+FB02. To see which characters a particular font supports, open the **Fonts** applet in Control Panel, choose the **Find a character** option, and choose the font whose character set you'd like to examine in the **Font** list of the **Character Map** window. - -Windows uses font linking to display glyphs that are not available in a particular font. For information about font linking to display additional character sets, see [Globalization Step-by-Step: Fonts](https://go.microsoft.com/fwlink/?LinkId=229111). Linked fonts are defined in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontLink\SystemLink subkey of the registry. Each entry associated with this subkey corresponds to the name of a base font, and its value is a string array that defines the font files and the fonts that are linked to the base font. Each member of the array defines a linked font and takes the form *font-file-name*,*font-name*. The following example illustrates how you can programmatically define a linked font named SimSun found in a font file named simsun.ttc that displays Simplified Han characters. - -:::code language="csharp" source="./snippets/System/Console/Overview/csharp/fontlink1.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Console/Overview/vb/fontlink1.vb" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Console/Overview/fsharp/fontlink1.fs" id="Snippet2"::: - -Unicode support for the console has the following limitations: - -- UTF-32 encoding is not supported. The only supported Unicode encodings are UTF-8 and UTF-16, which are represented by the and classes, respectively. - -- Bidirectional output is not supported. - -- Display of characters outside the Basic Multilingual Plane (that is, of surrogate pairs) is not supported, even if they are defined in a linked font file. - -- Display of characters in complex scripts is not supported. - -- Combining character sequences (that is, characters that consist of a base character and one or more combining characters) are displayed as separate characters. To work around this limitation, you can normalize the string to be displayed by calling the method before sending output to the console. In the following example, a string that contains the combining character sequence U+0061 U+0308 is displayed to the console as two characters before the output string is normalized, and as a single character after the method is called. - - :::code language="csharp" source="./snippets/System/Console/Overview/csharp/normalize1.cs" id="Snippet5"::: - :::code language="vb" source="./snippets/System/Console/Overview/vb/normalize1.vb" id="Snippet5"::: - :::code language="fsharp" source="./snippets/System/Console/Overview/fsharp/normalize1.fs" id="Snippet5"::: - - Normalization is a viable solution only if the Unicode standard for the character includes a pre-composed form that corresponds to a particular combining character sequence. - -- If a font provides a glyph for a code point in the private use area, that glyph will be displayed. However, because characters in the private use area are application-specific, this may not be the expected glyph. - -The following example displays a range of Unicode characters to the console. The example accepts three command-line parameters: the start of the range to display, the end of the range to display, and whether to use the current console encoding (`false`) or UTF-16 encoding (`true`). It assumes that the console is using a TrueType font. - -:::code language="csharp" source="./snippets/System/Console/Overview/csharp/example3.cs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/Console/Overview/vb/example3.vb" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/Console/Overview/fsharp/example3.fs" id="Snippet4"::: - -## Common operations - -The class contains the following methods for reading console input and writing console output: - -- The overloads of the method read an individual character. - -- The method reads an entire line of input. - -- The method overloads convert an instance of a value type, an array of characters, or a set of objects to a formatted or unformatted string, and then write that string to the console. - -- A parallel set of method overloads output the same string as the overloads but also add a line termination string. - -The class also contains methods and properties to perform the following operations: - -- Get or set the size of the screen buffer. The and properties let you get or set the buffer height and width, respectively, and the method lets you set the buffer size in a single method call. - -- Get or set the size of the console window. The and properties let you get or set the window height and width, respectively, and the method lets you set the window size in a single method call. - -- Get or set the size of the cursor. The property specifies the height of the cursor in a character cell. - -- Get or set the position of the console window relative to the screen buffer. The and properties let you get or set the top row and leftmost column of the screen buffer that appears in the console window, and the method lets you set these values in a single method call. - -- Get or set the position of the cursor by getting or setting the and properties, or set the position of the cursor by calling the method. - -- Move or clear data in the screen buffer by calling the or method. - -- Get or set the foreground and background colors by using the and properties, or reset the background and foreground to their default colors by calling the method. - -- Play the sound of a beep through the console speaker by calling the method. - -## .NET Core notes - -In .NET Framework on the desktop, the class uses the encoding returned by `GetConsoleCP` and `GetConsoleOutputCP`, which typically is a code page encoding. For example code, on systems whose culture is English (United States), code page 437 is the encoding that is used by default. However, .NET Core may make only a limited subset of these encodings available. Where this is the case, is used as the default encoding for the console. - -If your app depends on specific code page encodings, you can still make them available by doing the following *before* you call any methods: - -1. Retrieve the object from the property. - -2. Pass the object to the method to make the additional encodings supported by the encoding provider available. - -The class will then automatically use the default system encoding rather than UTF8, provided that you have registered the encoding provider before calling any output methods. - -## Examples - -The following example demonstrates how to read data from, and write data to, the standard input and output streams. Note that these streams can be redirected by using the and methods. - -:::code language="csharp" source="./snippets/System/Console/Overview/csharp/source.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Console/Overview/vb/source.vb" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Console/Overview/fsharp/source.fs" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-convert.md b/docs/fundamentals/runtime-libraries/system-convert.md deleted file mode 100644 index 9512b39050943..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-convert.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: System.Convert class -description: Learn about the System.Convert class through these additional API remarks. -ms.date: 01/02/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Convert class - -[!INCLUDE [context](includes/context.md)] - -The static class contains methods that are primarily used to support conversion to and from the base data types in .NET. The supported base types are , , , , , , , , , , , , , and . In addition, the class includes methods to support other kinds of conversions. - -## Conversions to and from base types - -A conversion method exists to convert every base type to every other base type. However, the actual call to a particular conversion method can produce one of five outcomes, depending on the value of the base type at runtime and the target base type. These five outcomes are: - -- No conversion. This occurs when an attempt is made to convert from a type to itself (for example, by calling with an argument of type ). In this case, the method simply returns an instance of the original type. - -- An . This occurs when a particular conversion is not supported. An is thrown for the following conversions: - - - Conversions from to , , , , or . - - Conversions from , , , , or to . - - Conversions from to any other type except . - - Conversions from any other type, except , to . - -- A . This occurs when the attempt to convert a string value to any other base type fails because the string is not in the proper format. The exception is thrown for the following conversions: - - - A string to be converted to a value does not equal or . - - A string to be converted to a value consists of multiple characters. - - A string to be converted to any numeric type is not recognized as a valid number. - - A string to be converted to a is not recognized as a valid date and time value. - -- A successful conversion. For conversions between two different base types not listed in the previous outcomes, all widening conversions as well as all narrowing conversions that do not result in a loss of data will succeed and the method will return a value of the targeted base type. - -- An . This occurs when a narrowing conversion results in a loss of data. For example, trying to convert a instance whose value is 10000 to a type throws an because 10000 is outside the range of the data type. - -An exception will not be thrown if the conversion of a numeric type results in a loss of precision (that is, the loss of some least significant digits). However, an exception will be thrown if the result is larger than can be represented by the particular conversion method's return value type. - -For example, when a is converted to a , a loss of precision might occur but no exception is thrown. However, if the magnitude of the is too large to be represented by a , an overflow exception is thrown. - -## Non-decimal numbers - -The class includes static methods that you can call to convert integral values to non-decimal string representations, and to convert strings that represent non-decimal numbers to integral values. Each of these conversion methods includes a `base` argument that lets you specify the number system; binary (base 2), octal (base 8), and hexadecimal (base 16), as well as decimal (base 10). There is a set of methods to convert each of the CLS-compliant primitive integral types to a string, and one to convert a string to each of the primitive integral types: - -- and , to convert a byte value to and from a string in a specified base. - -- and , to convert a 16-bit signed integer to and from a string in a specified base. - -- and , to convert a 32-bit signed integer to and from a string in a specified base. - -- and , to convert a 64-bit signed integer to and from a string in a specified base. - -- , to convert the string representation of a byte value in a specified format to a signed byte. - -- , to convert the string representation of an integer in a specified format to an unsigned 16-bit integer. - -- , to convert the string representation of an integer in a specified format to an unsigned 32-bit integer. - -- , to convert the string representation of an integer in a specified format to an unsigned 64-bit integer. - -The following example converts the value of to a string in all supported numeric formats. It then converts the string value back to a value. - -:::code language="csharp" source="./snippets/System/Convert/Overview/csharp/NonDecimal1.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Convert/Overview/fsharp/NonDecimal1.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Convert/Overview/vb/NonDecimal1.vb" id="Snippet2"::: - -## Conversions from custom objects to base types - -In addition to supporting conversions between the base types, the method supports conversion of any custom type to any base type. To do this, the custom type must implement the interface, which defines methods for converting the implementing type to each of the base types. Conversions that are not supported by a particular type should throw an . - -When the method is passed a custom type as its first parameter, or when the `Convert.To`*Type* method (such as or is called and passed an instance of a custom type as its first parameter, the method, in turn, calls the custom type's implementation to perform the conversion. For more information, see [Type Conversion in .NET](../../standard/base-types/type-conversion.md). - -## Culture-specific formatting information - -All the base type conversion methods and the method include overloads that have a parameter of type . For example, the method has the following two overloads: - -- -- - -The parameter can supply culture-specific formatting information to assist the conversion process. However, it is ignored by most of the base type conversion methods. It is used only by the following base type conversion methods. If a `null` argument is passed to these methods, the object that represents the current culture is used. - -- By methods that convert a value to a numeric type. The parameter is used by the overload that has parameters of type and . It is also used by the overload that has parameters of type and if the object's runtime type is a . - -- By methods that convert a value to a date and time. The parameter is used by the overload that has parameters of type and . It is also used by the overload that has parameters of type and if the object's runtime type is a . - -- By the overloads that include an parameter and that convert either a numeric value to a string or a value to a string. - -However, any user-defined type that implements can make use of the parameter. - -## Base64 encoding - -Base64 encoding converts binary data to a string. Data expressed as base-64 digits can be easily conveyed over data channels that can only transmit 7-bit characters. The class includes the following methods to support base64 encoding: A set of methods support converting an array of bytes to and from a or to and from an array of Unicode characters consisting of base-64 digit characters. - -- , which converts a byte array to a base64-encoded string. -- , which converts a byte array to a base64-encoded character array. -- , which converts a base64-encoded string to a byte array. -- , which converts a base64-encoded character array to a byte array. - -## Other common conversions - -You can use other .NET classes to perform some conversions that aren't supported by the static methods of the class. These include: - -- Conversion to byte arrays - - The class provides methods that convert the primitive numeric types (including ) to byte arrays and from byte arrays back to primitive data types. - -- Character encoding and decoding - - The class and its derived classes (such as and ) provide methods to encode a character array or a string (that is, to convert them to a byte array in a particular encoding) and to decode an encoded byte array (that is, convert a byte array back to UTF16-encoded Unicode characters). For more information, see [Character Encoding in .NET](../../standard/base-types/character-encoding.md). - -## Examples - -The following example demonstrates some of the conversion methods in the class, including , , and . - -:::code language="csharp" source="./snippets/System/Convert/Overview/csharp/converter.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Convert/Overview/fsharp/converter.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Convert/Overview/vb/converter.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-data-commandbehavior.md b/docs/fundamentals/runtime-libraries/system-data-commandbehavior.md deleted file mode 100644 index 1aa02b5dd588a..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-data-commandbehavior.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: System.Data.CommandBehavior enum -description: Learn about the System.Data.CommandBehavior enum through these additional API remarks. -ms.date: 01/02/2024 ---- -# System.Data.CommandBehavior enum - -[!INCLUDE [context](includes/context.md)] - -The `CommandBehavior` values are used by the method of and any implementing classes. - -A bitwise combination of these values may be used. - -`CommandBehavior` is ignored when used to define a or and should therefore not be used. Use the constructor that does not require a `CommandBehavior` parameter in these two cases. - -## Notes on individual enumeration members - -When using `KeyInfo`, .NET Framework Data Provider for SQL Server precedes the statement being executed with `SET FMTONLY OFF` and `SET NO_BROWSETABLE ON`. Users should be aware of potential side effects, such as interference with the use of `SET FMTONLY ON` statements. For more information, see [SET FMTONLY (Transact-SQL)](/sql/t-sql/statements/set-fmtonly-transact-sql). - -> [!NOTE] -> Use `SequentialAccess` to retrieve large values and binary data. Otherwise, an might occur and the connection will be closed. - -When you specify `SequentialAccess`, you are required to read from the columns in the order they are returned, although you are not required to read each column. Once you have read past a location in the returned stream of data, data at or before that location can no longer be read from the `DataReader`. When using the , you can reread the current column value until reading past it. When using the , you can read a column value only once. diff --git a/docs/fundamentals/runtime-libraries/system-data-datacolumn-expression.md b/docs/fundamentals/runtime-libraries/system-data-datacolumn-expression.md deleted file mode 100644 index 4b1b5cb12f46a..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-data-datacolumn-expression.md +++ /dev/null @@ -1,298 +0,0 @@ ---- -title: System.Data.DataColumn.Expression property -description: Learn about the System.Data.DataColumn.Expression property. -ms.date: 01/24/2024 ---- -# System.Data.DataColumn.Expression property - -[!INCLUDE [context](includes/context.md)] - -One use of the property is to create calculated columns. For example, to calculate a tax value, the unit price is multiplied by a tax rate of a specific region. Because tax rates vary from region to region, it would be impossible to put a single tax rate in a column; instead, the value is calculated using the property, as shown in the following code: - -```vb -DataSet1.Tables("Products").Columns("tax").Expression = "UnitPrice * 0.086" -``` - -A second use is to create an aggregate column. Similar to a calculated value, an aggregate performs an operation based on the complete set of rows in the . A simple example is to count the number of rows returned in the set. This is the method you would use to count the number of transactions completed by a particular salesperson, as shown in the following code: - -```vb -DataSet1.Tables("Orders").Columns("OrderCount").Expression = "Count(OrderID)" -``` - -## Expression syntax - -When you create an expression, use the property to refer to columns. For example, if the for one column is "UnitPrice", and another "Quantity", the expression is: - -`"UnitPrice * Quantity"` - -> [!NOTE] -> If a column is used in an expression, then the expression is said to have a dependency on that column. If a dependent column is renamed or removed, no exception is thrown. An exception will be thrown when the now-broken expression column is accessed. - -When you create an expression for a filter, enclose strings with single quotation marks: - -`"LastName = 'Jones'"` - -If a column name contains any non-alphanumeric characters, starts with a digit, or matches (case-insensitively) any of the following reserved words, it requires special handling, as described in the following paragraphs. - -:::row::: - :::column::: - `And` - :::column-end::: - :::column::: - `Between` - :::column-end::: - :::column::: - `Child` - :::column-end::: - :::column::: - `False` - :::column-end::: -:::row-end::: -:::row::: - :::column::: - `In` - :::column-end::: - :::column::: - `Is` - :::column-end::: - :::column::: - `Like` - :::column-end::: - :::column::: - `Not` - :::column-end::: -:::row-end::: -:::row::: - :::column::: - `Null` - :::column-end::: - :::column::: - `Or` - :::column-end::: - :::column::: - `Parent` - :::column-end::: - :::column::: - `True` - :::column-end::: -:::row-end::: - -If a column name satisfies one of the previous conditions, it must be wrapped in either square brackets or "\`" (grave accent) quotes. For example, to use a column named "Column#" in an expression, you would write either "[Column#]" or "\`Column#`": - -`Total * [Column#]` - -If the column name is enclosed in square brackets, then any ']' and '\\' characters (but not any other characters) in it must be escaped by prepending them with the backslash ("\\") character. If the column name is enclosed in grave accent characters, then it must not contain any grave accent characters. For example, a column named "Column[]\\" would be written: - -`Total * [Column[\]\\]` - -or - -Total * \`Column[]\\` - -## User-defined values - -User-defined values may be used within expressions to be compared with column values. String values should be enclosed within single quotation marks (and each single quotation character in a string value has to be escaped by prepending it with another single quotation character). Date values should be enclosed within pound signs (#) or single quotes (') based on the data provider. Decimals and scientific notation are permissible for numeric values. For example: - -`"FirstName = 'John'"` - -`"Price <= 50.00"` - -`"Birthdate < #1/31/2006#"` - -For columns that contain enumeration values, cast the value to an integer data type. For example: - -`"EnumColumn = 5"` - -## Parse literal expressions - -All literal expressions must be expressed in the invariant culture locale. When `DataSet` parses and converts literal expressions, it always uses the invariant culture, not the current culture. - -String literals are identified when there are single quotes surrounding the value. For example, `'John'`. - -`Boolean` literals are `true` and `false`; they aren't quoted in expressions. - -`Integer` literals [+-]?[0-9]+ are treated as `System.Int32`, `System.Int64`, or `System.Double`. `System.Double` can lose precision depending on how large the number is. For example, if the number in the literal is 2147483650, `DataSet` will first attempt to parse the number as an `Int32`. This won't succeed because the number is too large. In this case `DataSet`, parses the number as an `Int64`, which will succeed. If the literal is a number larger than the maximum value of an Int64, `DataSet` parses the literal using `Double`. - -Real literals that use scientific notation, such as 4.42372E-30, are parsed using `System.Double`. - -Real literals without scientific notation, but with a decimal point, are treated as `System.Decimal`. If the number exceeds the maximum or minimum values supported by `System.Decimal`, then it is parsed as a `System.Double`. For example: - -- 142526.144524 is converted to a `Decimal`. -- 345262.78036719560925667 is treated as a `Double`. - -## Operators - -Concatenation is allowed using Boolean AND, OR, and NOT operators. You can use parentheses to group clauses and force precedence. The AND operator has precedence over other operators. For example: - -`(LastName = 'Smith' OR LastName = 'Jones') AND FirstName = 'John'` - -When you create comparison expressions, the following operators are allowed: - -- \< -- \> -- \<= -- \>= -- = -- `IN` -- `LIKE` - -The following arithmetic operators are also supported in expressions: - -- \+ (addition) -- \- (subtraction) -- \* (multiplication) -- / (division) -- % (modulus) - -## String operators - -To concatenate a string, use the `+` character. The value of the property of the class determines whether string comparisons are case-sensitive. However, you can override that value with the property of the class. - -## Wildcard characters - -Both the `*` and `%` characters can be used interchangeably for wildcard characters in a LIKE comparison. If the string in a LIKE clause contains a `*` or `%`, those characters should be enclosed in brackets (`[]`). If a bracket is in the clause, each bracket character should be enclosed in brackets (for example `[[]` or `[]]`). A wildcard is allowed at the start and end of a pattern, or at the end of a pattern, or at the start of a pattern. For example: - -- `"ItemName LIKE '*product*'"` -- `"ItemName LIKE '*product'"` -- `"ItemName LIKE 'product*'"` - -Wildcard characters are not allowed in the middle of a string. For example, `'te*xt'` is not allowed. - -## Parent/child relation referencing - -A parent table may be referenced in an expression by prepending the column name with `Parent`. For example, `Parent.Price` references the parent table's column named `Price`. - -When a child has more than one parent row, use `Parent(RelationName).ColumnName`. For example, `Parent(RelationName).Price` references the parent table's column named "Price" via the relation. - -A column in a child table may be referenced in an expression by prepending the column name with `Child`. However, because child relationships may return multiple rows, you must include the reference to the child column in an aggregate function. For example, `Sum(Child.Price)` would return the sum of the column named `Price` in the child table. - -If a table has more than one child, the syntax is: `Child(RelationName)`. For example, if a table has two child tables named `Customers` and `Orders`, and the object is named `Customers2Orders`, the reference would be as follows: - -`Avg(Child(Customers2Orders).Quantity)` - -## Aggregates - -The following aggregate types are supported: - -- `Sum` (Sum) -- `Avg` (Average) -- `Min` (Minimum) -- `Max` (Maximum) -- `Count` (Count) -- `StDev` (Statistical standard deviation) -- `Var` (Statistical variance) - -Aggregates are ordinarily performed along relationships. Create an aggregate expression by using one of the functions listed earlier and a child table column as detailed in [Parent/child relation referencing](#parentchild-relation-referencing). For example: - -- `Avg(Child.Price)` -- `Avg(Child(Orders2Details).Price)` - -An aggregate can also be performed on a single table. For example, to create a summary of figures in a column named "Price": - -`Sum(Price)` - -> [!NOTE] -> If you use a single table to create an aggregate, there would be no group-by functionality. Instead, all rows would display the same value in the column. - -If a table has no rows, the aggregate functions will return `null`. - -Data types can always be determined by examining the property of a column. You can also convert data types using the `Convert` function, shown in the following section. - -An aggregate can only be applied to a single column, and no other expressions can be used inside the aggregate. - -## Functions - -The following functions are also supported. - -### `CONVERT` - -This function converts an expression to a specified .NET type. - -```csharp -Convert(expression, type) -``` - -| Argument | Description | -|--------------|-------------------------------------------------| -| `expression` | The expression to convert. | -| `type` | .NET type to which the value will be converted. | - -Example: `myDataColumn.Expression="Convert(total, 'System.Int32')"` - -All conversions are valid with the following exceptions: `Boolean` can be coerced to and from `Byte`, `SByte`, `Int16`, `Int32`, `Int64`, `UInt16`, `UInt32`, `UInt64`, `String` and itself only. `Char` can be coerced to and from `Int32`, `UInt32`, `String`, and itself only. `DateTime` can be coerced to and from `String` and itself only. `TimeSpan` can be coerced to and from `String` and itself only. - -### `LEN` - -This function gets the length of a string. - -```csharp -LEN(expression) -``` - -| Arguments | Description | -|--------------|-----------------------------| -| `expression` | The string to be evaluated. | - -Example: `myDataColumn.Expression="Len(ItemName)"` - -### `ISNULL` - -This function checks an expression and either returns the checked expression or a replacement value. - -```csharp -ISNULL(expression, replacementvalue) -``` - -| Arguments | Description | -|--------------------|----------------------------------------------------------| -| `expression` | The expression to check. | -| `replacementvalue` | If expression is `null`, `replacementvalue` is returned. | - -Example: `myDataColumn.Expression="IsNull(price, -1)"` - -### `IIF` - -This function gets one of two values depending on the result of a logical expression. - -```csharp -IIF(expr, truepart, falsepart) -``` - -| Arguments | Description | -|-------------|-------------------------------------------------| -| `expr` | The expression to evaluate. | -| `truepart` | The value to return if the expression is true. | -| `falsepart` | The value to return if the expression is false. | - -Example: `myDataColumn.Expression = "IIF(total>1000, 'expensive', 'dear')` - -### `TRIM` - -This function removes all leading and trailing blank characters like \r, \n, \t, and ' '. - -```csharp -TRIM(expression) -``` - -| Argument | Description | -|--------------|-------------------------| -| `expression` | The expression to trim. | - -### `SUBSTRING` - -This function gets a substring of a specified length, starting at a specified point in the string. - -```csharp -SUBSTRING(expression, start, length) -``` - -| Argument | Description | -|--------------|-----------------------------------------------------| -| `expression` | The source string for the substring | -| `start` | Integer that specifies where the substring starts. | -| `length` | Integer that specifies the length of the substring. | - -Example: `myDataColumn.Expression = "SUBSTRING(phone, 7, 8)"` - -> [!NOTE] -> You can reset the property by assigning it a null value or empty string. If a default value is set on the expression column, all previously filled rows are assigned the default value after the property is reset. diff --git a/docs/fundamentals/runtime-libraries/system-data-dataset.md b/docs/fundamentals/runtime-libraries/system-data-dataset.md deleted file mode 100644 index 7bc31be686aaf..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-data-dataset.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: System.Data.DataSet class -description: Learn about the System.Data.DataSet class through these additional API remarks. -ms.date: 01/02/2024 ---- -# System.Data.DataSet class - -[!INCLUDE [context](includes/context.md)] - -The class, which is an in-memory cache of data retrieved from a data source, is a major component of the ADO.NET architecture. The consists of a collection of objects that you can relate to each other with objects. You can also enforce data integrity in the by using the and objects. For further details about working with objects, see [DataSets, DataTables, and DataViews](../../framework/data/adonet/dataset-datatable-dataview/index.md). - -Whereas objects contain the data, the allows you to navigate though the table hierarchy. The tables are contained in a accessed through the property. When accessing objects, note that they are conditionally case sensitive. For example, if one is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. For more information about working with objects, see [Creating a DataTable](../../framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md). - -A can read and write data and schema as XML documents. The data and schema can then be transported across HTTP and used by any application, on any platform that is XML-enabled. You can save the schema as an XML schema with the method, and both schema and data can be saved using the method. To read an XML document that includes both schema and data, use the method. - -In a typical multiple-tier implementation, the steps for creating and refreshing a , and in turn, updating the original data are to: - -1. Build and fill each in a with data from a data source using a . - -2. Change the data in individual objects by adding, updating, or deleting objects. - -3. Invoke the method to create a second that features only the changes to the data. - -4. Call the method of the , passing the second as an argument. - -5. Invoke the method to merge the changes from the second into the first. - -6. Invoke the on the . Alternatively, invoke to cancel the changes. - -> [!NOTE] -> The and objects inherit from , and support the interface for remoting. These are the only ADO.NET objects that can be remoted. - -> [!NOTE] -> Classes inherited from are not finalized by the garbage collector, because the finalizer has been suppressed in . The derived class can call the method in its constructor to allow the class to be finalized by the garbage collector. - -## Security considerations - -For information about DataSet and DataTable security, see [Security guidance](../../framework/data/adonet/dataset-datatable-dataview/security-guidance.md). diff --git a/docs/fundamentals/runtime-libraries/system-data-datatable.md b/docs/fundamentals/runtime-libraries/system-data-datatable.md deleted file mode 100644 index 3534a00e05884..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-data-datatable.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: System.Data.DataTable class -description: Learn about the System.Data.DataTable class through these additional API remarks. -ms.date: 01/02/2024 -dev_langs: - - CSharp - - VB ---- -# System.Data.DataTable class - -[!INCLUDE [context](includes/context.md)] - -The class is a central object in the ADO.NET library. Other objects that use include the and the . - - object names are conditionally case sensitive. For example, if one is named "mydatatable" and another is named "Mydatatable", a string used to search for one of the tables is regarded as case sensitive. However, if "mydatatable" exists and "Mydatatable" does not, the search string is regarded as case insensitive. A can contain two objects that have the same property value but different property values. For more information about working with objects, see [Creating a DataTable](../../framework/data/adonet/dataset-datatable-dataview/creating-a-datatable.md). - -If you're creating a programmatically, you must first define its schema by adding objects to the (accessed through the property). For more information about adding objects, see [Adding Columns to a DataTable](../../framework/data/adonet/dataset-datatable-dataview/adding-columns-to-a-datatable.md). - -To add rows to a , you must first use the method to return a new object. The method returns a row with the schema of the , as it is defined by the table's . The maximum number of rows that a can store is 16,777,216. For more information, see [Adding Data to a DataTable](../../framework/data/adonet/dataset-datatable-dataview/adding-data-to-a-datatable.md). - -The also contains a collection of objects that can be used to ensure the integrity of the data. For more information, see [DataTable Constraints](../../framework/data/adonet/dataset-datatable-dataview/datatable-constraints.md). - -There are many events that can be used to determine when changes are made to a table. These include , , , and . For more information about the events that can be used with a , see [Handling DataTable Events](../../framework/data/adonet/dataset-datatable-dataview/handling-datatable-events.md). - -When an instance of is created, some of the read/write properties are set to initial values. For a list of these values, see the constructor. - -> [!NOTE] -> The and objects inherit from and support the interface for .NET remoting. These are the only ADO.NET objects that you can use for .NET remoting. - -## Security considerations - -For information about DataSet and DataTable security, see [Security guidance](../../framework/data/adonet/dataset-datatable-dataview/security-guidance.md). - -## Examples - -This sample demonstrates how to create a DataTable manually with specific schema definitions: - -- Create multiple DataTables and define the initial columns. -- Create the table constraints. -- Insert the values and display the tables. -- Create the expression columns and display the tables. - -:::code language="csharp" source="./snippets/System.Data/DataTable/Overview/cs/source.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Data/DataTable/Overview/vb/source.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-datetime-tobinary.md b/docs/fundamentals/runtime-libraries/system-datetime-tobinary.md deleted file mode 100644 index 47a83cb06d389..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-datetime-tobinary.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -title: System.DateTime.ToBinary and FromBinary methods -description: Learn about the System.DateTime.ToBinary and System.DateTime.FromBinary methods. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.DateTime.ToBinary and FromBinary methods - -[!INCLUDE [context](includes/context.md)] - -Use the method to convert the value of the current object to a binary value. Subsequently, use the binary value and the method to recreate the original object. - -> [!IMPORTANT] -> In some cases, the value returned by the method is not identical to the original value supplied to the method. For more information, see the next section, "Local Time Adjustment". - -A structure consists of a private field, which indicates whether the specified time value is based on local time, Coordinated Universal Time (UTC), or neither, concatenated to a private field, which contains the number of 100-nanosecond ticks that specify a date and time. - -## Local time adjustment - -A local time, which is a Coordinated Universal Time adjusted to the local time zone, is represented by a structure whose property has the value . When restoring a local value from the binary representation that is produced by the method, the method may adjust the recreated value so that it is not equal to the original value. This can occur under the following conditions: - -- If a local object is serialized in one time zone by the method, and then deserialized in a different time zone by the method, the local time represented by the resulting object is automatically adjusted to the second time zone. - - For example, consider a object that represents a local time of 3 P.M. An application that is executing in the U.S. Pacific Time zone uses the method to convert that object to a binary value. Another application that is executing in the U.S. Eastern Time zone then uses the method to convert the binary value to a new object. The value of the new object is 6 P.M., which represents the same point in time as the original 3 P.M. value, but is adjusted to local time in the Eastern Time zone. - -- If the binary representation of a local value represents an invalid time in the local time zone of the system on which is called, the time is adjusted so that it is valid. - - For example, the transition from standard time to daylight saving time occurs in the Pacific Time zone of the United States on March 14, 2010, at 2:00 A.M., when the time advances by one hour, to 3:00 A.M. This hour interval is an invalid time, that is, a time interval that does not exist in this time zone. The following example shows that when a time that falls within this range is converted to a binary value by the method and is then restored by the method, the original value is adjusted to become a valid time. You can determine whether a particular date and time value may be subject to modification by passing it to the method, as the example illustrates. - - :::code language="csharp" source="./snippets/System/DateTime/FromBinary/csharp/frombinary1.cs" id="Snippet1"::: - :::code language="fsharp" source="./snippets/System/DateTime/FromBinary/fsharp/frombinary1.fs" id="Snippet1"::: - :::code language="vb" source="./snippets/System/DateTime/FromBinary/vb/frombinary1.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-datetime-tryparse.md b/docs/fundamentals/runtime-libraries/system-datetime-tryparse.md deleted file mode 100644 index 12942b5fa8d0d..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-datetime-tryparse.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: System.DateTime.TryParse method -description: Learn about the System.DateTime.TryParse method. -ms.date: 01/24/2024 ---- -# System.DateTime.TryParse method - -[!INCLUDE [context](includes/context.md)] - -The method parses a string that can contain date, time, and time zone information. It is similar to the method, except that the method does not throw an exception if the conversion fails. - -This method attempts to ignore unrecognized data and parse the input string (`s`) completely. If `s` contains a time but no date, the method by default substitutes the current date or, if `styles` includes the flag, it substitutes `DateTime.Date.MinValue`. If `s` contains a date but no time, 12:00 midnight is used as the default time. If a date is present but its year component consists of only two digits, it is converted to a year in the `provider` parameter's current calendar based on the value of the property. Any leading, inner, or trailing white space characters in `s` are ignored. The date and time can be bracketed with a pair of leading and trailing NUMBER SIGN characters ('#', U+0023), and can be trailed with one or more NULL characters (U+0000). - -Specific valid formats for date and time elements, as well as the names and symbols used in dates and times, are defined by the `provider` parameter, which can be any of the following: - -- A object that represents the culture whose formatting is used in the `s` parameter. The object returned by the property defines the formatting used in `s`. -- A object that defines the formatting used in `s`. -- A custom implementation. Its method returns a object that defines the formatting used in `s`. - -If `provider` is `null`, the current culture is used. - -If `s` is the string representation of a leap day in a leap year in the current calendar, the method parses `s` successfully. If `s` is the string representation of a leap day in a non-leap year in the current calendar of `provider`, the parse operation fails and the method returns `false`. - -The `styles` parameter defines the precise interpretation of the parsed string and how the parse operation should handle it. It can be one or more members of the enumeration, as described in the following table. - -|DateTimeStyles member|Description| -|---------------------------|-----------------| -||Parses `s` and, if necessary, converts it to UTC. If `s` includes a time zone offset, or if `s` contains no time zone information but `styles` includes the flag, the method parses the string, calls to convert the returned value to UTC, and sets the property to . If `s` indicates that it represents UTC, or if `s` does not contain time zone information but `styles` includes the flag, the method parses the string, performs no time zone conversion on the returned value, and sets the property to . In all other cases, the flag has no effect.| -||Although valid, this value is ignored. Inner white space is permitted in the date and time elements of `s`.| -||Although valid, this value is ignored. Leading white space is permitted in the date and time elements of `s`.| -||Although valid, this value is ignored. Trailing white space is permitted in the date and time elements of `s`.| -||Specifies that `s` may contain leading, inner, and trailing white spaces. This is the default behavior. It cannot be overridden by supplying a more restrictive enumeration value such as .| -||Specifies that if `s` lacks any time zone information, it is assumed to represent a local time. Unless the flag is present, the property of the returned value is set to .| -||Specifies that if `s` lacks any time zone information, it is assumed to represent UTC. Unless the flag is present, the method converts the returned value from UTC to local time and sets its property to .| -||Although valid, this value is ignored.| -||For strings that contain time zone information, tries to prevent the conversion of a date and time string to a value with its property set to . Typically, such a string is created by calling the method using either the "o", "r", or "u" standard format specifiers.| - -If `s` contains no time zone information, the method returns a value whose property is unless a `styles` flag indicates otherwise. If `s` includes time zone or time zone offset information, the method performs any necessary time conversion and returns one of the following: - -- A value whose date and time reflect the local time and whose property is . -- Or, if `styles` includes the flag, a value whose date and time reflect UTC and whose property is . - -This behavior can be overridden by using the flag. - -## Parse custom cultures - -If you parse a date and time string generated for a custom culture, use the method instead of the method to improve the probability that the parse operation will succeed. A custom culture date and time string can be complicated and difficult to parse. The method attempts to parse a string with several implicit parse patterns, all of which might fail. In contrast, the method requires you to explicitly designate one or more exact parse patterns that are likely to succeed. - -For more information about custom cultures, see the class. diff --git a/docs/fundamentals/runtime-libraries/system-datetime.md b/docs/fundamentals/runtime-libraries/system-datetime.md deleted file mode 100644 index ae0ae8fa6a2a2..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-datetime.md +++ /dev/null @@ -1,402 +0,0 @@ ---- -title: System.DateTime struct -description: Learn about the System.DateTime struct. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.DateTime struct - -[!INCLUDE [context](includes/context.md)] - -[!INCLUDE[japanese-era-note](./includes/calendar-era.md)] - -## Overview - -The value type represents dates and times with values ranging from 00:00:00 (midnight), January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.) in the Gregorian calendar. - -Time values are measured in 100-nanosecond units called ticks. A particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the calendar. The number excludes ticks that would be added by leap seconds. For example, a ticks value of 31241376000000000L represents the date Friday, January 01, 0100 12:00:00 midnight. A value is always expressed in the context of an explicit or default calendar. - -> [!NOTE] -> If you're working with a ticks value that you want to convert to some other time interval, such as minutes or seconds, you should use the , , , , or constant to perform the conversion. For example, to add the number of seconds represented by a specified number of ticks to the component of a value, you can use the expression `dateValue.Second + nTicks/Timespan.TicksPerSecond`. - -> [!NOTE] -> An alternative to the structure for working with date and time values in particular time zones is the structure. The structure stores date and time information in a private field and the number of minutes by which that date and time differs from UTC in a private field. This makes it possible for a value to reflect the time in a particular time zone, whereas a value can unambiguously reflect only UTC and the local time zone's time. For a discussion about when to use the structure or the structure when working with date and time values, see [Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo](../../standard/datetime/choosing-between-datetime.md). - -## Quick links to example code - -This article includes several examples that use the `DateTime` type: - -### Initialization examples - -- [Invoke a constructor](#initialization-01) -- [Invoke the implicit parameterless constructor](#initialization-02) -- [Assignment from return value](#initialization-03) -- [Parsing a string that represents a date and time](#initialization-04) -- [Visual Basic syntax to initialize a date and time](#initialization-05) - -### Format `DateTime` objects as strings examples - -- [Use the default date time format](#formatting-01) -- [Format a date and time using a specific culture](#formatting-02) -- [Format a date time using a standard or custom format string](#formatting-03) -- [Specify both a format string and a specific culture](#formatting-04) -- [Format a date time using the ISO 8601 standard for web services](#formatting-05) - -### Parse strings as `DateTime` objects examples - -- [Use `Parse` or `TryParse` to convert a string to a date and time](#parsing-01) -- [Use `ParseExact` or `TryParseExact` to convert a string in a known format](#parsing-02) -- [Convert from the ISO 8601 string representation to a date and time](#parsing-03) - -### `DateTime` resolution examples - -- [Explore the resolution of date and time values](#resolution-01) -- [Comparing for equality within a tolerance](#comparison-01) - -### Culture and calendars examples - -- [Display date and time values using culture specific calendars](#calendars-01) -- [Parse strings according to a culture specific calendar](#calendars-02) -- [Initialize a date and time from a specific culture's calendar](#calendars-03) -- [Accessing date and time properties using a specific culture's calendar](#calendars-04) -- [Retrieving the week of the year using culture specific calendars](#calendars-05) - -### Persistence examples - -- [Persisting date and time values as strings in the local time zone](#persistence-01) -- [Persisting date and time values as strings in a culture and time invariant format](#persistence-02) -- [Persisting date and time values as integers](#persistence-03) -- [Persisting date and time values using the `XmlSerializer`](#persistence-04) - -## Initialize a DateTime object - -You can assign an initial value to a new `DateTime` value in many different ways: - -- Calling a constructor, either one where you specify arguments for values, or use the implicit parameterless constructor. -- Assigning a `DateTime` to the return value of a property or method. -- Parsing a `DateTime` value from its string representation. -- Using Visual Basic-specific language features to instantiate a `DateTime`. - -The following code snippets show examples of each. - -### Invoke constructors - -You call any of the overloads of the constructor that specify elements of the date and time value (such as the year, month, and day, or the number of ticks). The following code creates a specific date using the constructor specifying the year, month, day, hour, minute, and second. - - -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Instantiation.vb" id="Snippet1"::: -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Instantiation.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Instantiation.fs" id="Snippet1"::: - -You invoke the `DateTime` structure's implicit parameterless constructor when you want a `DateTime` initialized to its default value. (For details on the implicit parameterless constructor of a value type, see [Value Types](/dotnet/csharp/language-reference/keywords/value-types).) Some compilers also support declaring a value without explicitly assigning a value to it. Creating a value without an explicit initialization also results in the default value. The following example illustrates the implicit parameterless constructor in C# and Visual Basic, as well as a declaration without assignment in Visual Basic. - - -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Instantiation.vb" id="Snippet5"::: -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Instantiation.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Instantiation.fs" id="Snippet5"::: - -### Assign a computed value - -You can assign the object a date and time value returned by a property or method. The following example assigns the current date and time, the current Coordinated Universal Time (UTC) date and time, and the current date to three new variables. - - -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Instantiation.vb" id="Snippet3"::: -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Instantiation.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Instantiation.fs" id="Snippet3"::: - -### Parse a string that represents a DateTime - -The , , , and methods all convert a string to its equivalent date and time value. The following examples use the and methods to parse a string and convert it to a value. The second format uses a form supported by the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) standard for a representing date and time in string format. This standard representation is often used to transfer date information in web services. - - -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Instantiation.vb" id="Snippet4"::: -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Instantiation.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Instantiation.fs" id="Snippet4"::: - -The and methods indicate whether a string is a valid representation of a value and, if it is, performs the conversion. - -### Language-specific syntax for Visual Basic - -The following Visual Basic statement initializes a new value. - - -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Instantiation.vb" id="Snippet2"::: - -## DateTime values and their string representations - -Internally, all values are represented as the number of ticks (the number of 100-nanosecond intervals) that have elapsed since 12:00:00 midnight, January 1, 0001. The actual value is independent of the way in which that value appears when displayed. The appearance of a value is the result of a formatting operation that converts a value to its string representation. - -The appearance of date and time values is dependent on culture, international standards, application requirements, and personal preference. The structure offers flexibility in formatting date and time values through overloads of . The default method returns the string representation of a date and time value using the current culture's short date and long time pattern. The following example uses the default method. It displays the date and time using the short date and long time pattern for the current culture. The en-US culture is the current culture on the computer on which the example was run. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/StringFormat.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/StringFormat.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/StringFormat.vb" id="Snippet1"::: - -You may need to format dates in a specific culture to support web scenarios where the server may be in a different culture from the client. You specify the culture using the method to create the short date and long time representation in a specific culture. The following example uses the method to display the date and time using the short date and long time pattern for the fr-FR culture. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/StringFormat.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/StringFormat.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/StringFormat.vb" id="Snippet2"::: - -Other applications may require different string representations of a date. The method returns the string representation defined by a standard or custom format specifier using the formatting conventions of the current culture. The following example uses the method to display the full date and time pattern for the en-US culture, the current culture on the computer on which the example was run. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/StringFormat.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/StringFormat.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/StringFormat.vb" id="Snippet3"::: - -Finally, you can specify both the culture and the format using the method. The following example uses the method to display the full date and time pattern for the fr-FR culture. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/StringFormat.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/StringFormat.fs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/StringFormat.vb" id="Snippet4"::: - -The overload can also be used with a custom format string to specify other formats. The following example shows how to format a string using the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) standard format often used for web services. The Iso 8601 format does not have a corresponding standard format string. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/StringFormat.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/StringFormat.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/StringFormat.vb" id="Snippet5"::: - -For more information about formatting values, see [Standard Date and Time Format Strings](../../standard/base-types/standard-date-and-time-format-strings.md) and [Custom Date and Time Format Strings](../../standard/base-types/custom-date-and-time-format-strings.md). - -## Parse DateTime values from strings - -Parsing converts the string representation of a date and time to a value. Typically, date and time strings have two different usages in applications: - -- A date and time takes a variety of forms and reflects the conventions of either the current culture or a specific culture. For example, an application allows a user whose current culture is en-US to input a date value as "12/15/2013" or "December 15, 2013". It allows a user whose current culture is en-gb to input a date value as "15/12/2013" or "15 December 2013." - -- A date and time is represented in a predefined format. For example, an application serializes a date as "20130103" independently of the culture on which the app is running. An application may require dates be input in the current culture's short date format. - -You use the or method to convert a string from one of the common date and time formats used by a culture to a value. The following example shows how you can use to convert date strings in different culture-specific formats to a value. It changes the current culture to English (United Kingdom) and calls the method to generate an array of date and time strings. It then passes each element in the array to the method. The output from the example shows the parsing method was able to successfully convert each of the culture-specific date and time strings. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Parsing.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Parsing.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Parsing.vb" id="Snippet1"::: - -You use the and methods to convert a string that must match a particular format or formats to a value. You specify one or more date and time format strings as a parameter to the parsing method. The following example uses the method to convert strings that must be either in a "yyyyMMdd" format or a "HHmmss" format to values. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Parsing.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Parsing.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Parsing.vb" id="Snippet2"::: - -One common use for is to convert a string representation from a web service, usually in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) standard format. The following code shows the correct format string to use: - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Parsing.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Parsing.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Parsing.vb" id="Snippet3"::: - -If a string cannot be parsed, the and methods throw an exception. The and methods return a value that indicates whether the conversion succeeded or failed. You should use the or methods in scenarios where performance is important. The parsing operation for date and time strings tends to have a high failure rate, and exception handling is expensive. Use these methods if strings are input by users or coming from an unknown source. - -For more information about parsing date and time values, see [Parsing Date and Time Strings](../../standard/base-types/parsing-datetime.md). - -## DateTime values - -Descriptions of time values in the type are often expressed using the Coordinated Universal Time (UTC) standard. Coordinated Universal Time is the internationally recognized name for Greenwich Mean Time (GMT). Coordinated Universal Time is the time as measured at zero degrees longitude, the UTC origin point. Daylight saving time is not applicable to UTC. - -Local time is relative to a particular time zone. A time zone is associated with a time zone offset. A time zone offset is the displacement of the time zone measured in hours from the UTC origin point. In addition, local time is optionally affected by daylight saving time, which adds or subtracts a time interval adjustment. Local time is calculated by adding the time zone offset to UTC and adjusting for daylight saving time if necessary. The time zone offset at the UTC origin point is zero. - -UTC time is suitable for calculations, comparisons, and storing dates and time in files. Local time is appropriate for display in user interfaces of desktop applications. Time zone-aware applications (such as many Web applications) also need to work with a number of other time zones. - -If the property of a object is , it is unspecified whether the time represented is local time, UTC time, or a time in some other time zone. - -## DateTime resolution - -> [!NOTE] -> As an alternative to performing date and time arithmetic on values to measure elapsed time, you can use the class. - -The property expresses date and time values in units of one ten-millionth of a second. The property returns the thousandths of a second in a date and time value. Using repeated calls to the property to measure elapsed time is dependent on the system clock. The system clock on Windows 7 and Windows 8 systems has a resolution of approximately 15 milliseconds. This resolution affects small time intervals less than 100 milliseconds. - -The following example illustrates the dependence of current date and time values on the resolution of the system clock. In the example, an outer loop repeats 20 times, and an inner loop serves to delay the outer loop. If the value of the outer loop counter is 10, a call to the method introduces a five-millisecond delay. The following example shows the number of milliseconds returned by the `DateTime.Now.Milliseconds` property changes only after the call to . - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Resolution.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Resolution.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Resolution.vb" id="Snippet1"::: - -## DateTime operations - -A calculation using a structure, such as or , does not modify the value of the structure. Instead, the calculation returns a new structure whose value is the result of the calculation. - -Conversion operations between time zones (such as between UTC and local time, or between one time zone and another) take daylight saving time into account, but arithmetic and comparison operations do not. - -The structure itself offers limited support for converting from one time zone to another. You can use the method to convert UTC to local time, or you can use the method to convert from local time to UTC. However, a full set of time zone conversion methods is available in the class. You convert the time in any one of the world's time zones to the time in any other time zone using these methods. - -Calculations and comparisons of objects are meaningful only if the objects represent times in the same time zone. You can use a object to represent a value's time zone, although the two are loosely coupled. A object does not have a property that returns an object that represents that date and time value's time zone. The property indicates if a `DateTime` represents UTC, local time, or is unspecified. In a time zone-aware application, you must rely on some external mechanism to determine the time zone in which a object was created. You could use a structure that wraps both the value and the object that represents the value's time zone. For details on using UTC in calculations and comparisons with values, see [Performing Arithmetic Operations with Dates and Times](../../standard/datetime/performing-arithmetic-operations.md). - -Each member implicitly uses the Gregorian calendar to perform its operation. Exceptions are methods that implicitly specify a calendar. These include constructors that specify a calendar, and methods with a parameter derived from , such as . - -Operations by members of the type take into account details such as leap years and the number of days in a month. - -## DateTime values and calendars - -The .NET Class Library includes a number of calendar classes, all of which are derived from the class. They are: - -- The class. -- The class. -- The class. -- The class. -- The class. -- The class. -- The class. -- The class. -- The class. -- The class. -- The class. -- The class. -- The class. -- The class. -- The class. - -[!INCLUDE[japanese-era-note](./includes/calendar-era.md)] - -Each culture uses a default calendar defined by its read-only property. Each culture may support one or more calendars defined by its read-only property. The calendar currently used by a specific object is defined by its property. It must be one of the calendars found in the array. - -A culture's current calendar is used in all formatting operations for that culture. For example, the default calendar of the Thai Buddhist culture is the Thai Buddhist Era calendar, which is represented by the class. When a object that represents the Thai Buddhist culture is used in a date and time formatting operation, the Thai Buddhist Era calendar is used by default. The Gregorian calendar is used only if the culture's property is changed, as the following example shows: - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Calendar.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Calendar.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Calendar.vb" id="Snippet1"::: - -A culture's current calendar is also used in all parsing operations for that culture, as the following example shows. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Calendar.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Calendar.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Calendar.vb" id="Snippet2"::: - -You instantiate a value using the date and time elements (number of the year, month, and day) of a specific calendar by calling a [DateTime constructor](xref:System.DateTime.%23ctor*) that includes a `calendar` parameter and passing it a object that represents that calendar. The following example uses the date and time elements from the calendar. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Calendar.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Calendar.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Calendar.vb" id="Snippet3"::: - - constructors that do not include a `calendar` parameter assume that the date and time elements are expressed as units in the Gregorian calendar. - -All other properties and methods use the Gregorian calendar. For example, the property returns the year in the Gregorian calendar, and the method assumes that the `year` parameter is a year in the Gregorian calendar. Each member that uses the Gregorian calendar has a corresponding member of the class that uses a specific calendar. For example, the method returns the year in a specific calendar, and the method interprets the `year` parameter as a year number in a specific calendar. The following example uses both the and the corresponding members of the class. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Calendar.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Calendar.fs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Calendar.vb" id="Snippet4"::: - -The structure includes a property that returns the day of the week in the Gregorian calendar. It does not include a member that allows you to retrieve the week number of the year. To retrieve the week of the year, call the individual calendar's method. The following example provides an illustration. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Calendar.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Calendar.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/Calendar.vb" id="Snippet5"::: - -For more information on dates and calendars, see [Working with Calendars](../../standard/datetime/working-with-calendars.md). - -## Persist DateTime values - -You can persist values in the following ways: - -- [Convert them to strings](#persist-values-as-strings) and persist the strings. -- [Convert them to 64-bit integer values](#persist-values-as-integers) (the value of the property) and persist the integers. -- [Serialize the DateTime values](#serializing-datetime-values). - -You must ensure that the routine that restores the values doesn't lose data or throw an exception regardless of which technique you choose. values should round-trip. That is, the original value and the restored value should be the same. And if the original value represents a single instant of time, it should identify the same moment of time when it's restored. - -### Persist values as strings - -To successfully restore values that are persisted as strings, follow these rules: - -- Make the same assumptions about culture-specific formatting when you restore the string as when you persisted it. To ensure that a string can be restored on a system whose current culture is different from the culture of the system it was saved on, call the overload to save the string by using the conventions of the invariant culture. Call the or overload to restore the string by using the conventions of the invariant culture. Never use the , , or overloads, which use the conventions of the current culture. - -- If the date represents a single moment of time, ensure that it represents the same moment in time when it's restored, even on a different time zone. Convert the value to Coordinated Universal Time (UTC) before saving it or use . - -The most common error made when persisting values as strings is to rely on the formatting conventions of the default or current culture. Problems arise if the current culture is different when saving and restoring the strings. The following example illustrates these problems. It saves five dates using the formatting conventions of the current culture, which in this case is English (United States). It restores the dates using the formatting conventions of a different culture, which in this case is English (United Kingdom). Because the formatting conventions of the two cultures are different, two of the dates can't be restored, and the remaining three dates are interpreted incorrectly. Also, if the original date and time values represent single moments in time, the restored times are incorrect because time zone information is lost. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Persistence.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Persistence.fs" id="Snippet1"::: - -To round-trip values successfully, follow these steps: - -1. If the values represent single moments of time, convert them from the local time to UTC by calling the method. -1. Convert the dates to their string representations by calling the or overload. Use the formatting conventions of the invariant culture by specifying as the `provider` argument. Specify that the value should round-trip by using the "O" or "R" standard format string. - -To restore the persisted values without data loss, follow these steps: - -1. Parse the data by calling the or overload. Specify as the `provider` argument, and use the same standard format string you used for the `format` argument during conversion. Include the value in the `styles` argument. -1. If the values represent single moments in time, call the method to convert the parsed date from UTC to local time. - -The following example uses the invariant culture and the "O" standard format string to ensure that values saved and restored represent the same moment in time regardless of the system, culture, or time zone of the source and target systems. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Persistence.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Persistence.fs" id="Snippet2"::: - -### Persist values as integers - -You can persist a date and time as an value that represents a number of ticks. In this case, you don't have to consider the culture of the systems the values are persisted and restored on. - -To persist a value as an integer: - -1. If the values represent single moments in time, convert them to UTC by calling the method. -1. Retrieve the number of ticks represented by the value from its property. - -To restore a value that has been persisted as an integer: - -1. Instantiate a new object by passing the value to the constructor. -1. If the value represents a single moment in time, convert it from UTC to the local time by calling the method. - -The following example persists an array of values as integers on a system in the U.S. Pacific Time zone. It restores it on a system in the UTC zone. The file that contains the integers includes an value that indicates the total number of values that immediately follow it. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Persistence.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Persistence.fs" id="Snippet3"::: - - - -### Serialize DateTime values - -You can persist values through serialization to a stream or file, and then restore them through deserialization. data is serialized in some specified object format. The objects are restored when they are deserialized. A formatter or serializer, such as or , handles the process of serialization and deserialization. For more information about serialization and the types of serialization supported by .NET, see [Serialization](../../standard/serialization/index.md). - -The following example uses the class to serialize and deserialize values. The values represent all leap year days in the twenty-first century. The output represents the result if the example is run on a system whose current culture is English (United Kingdom). Because you've deserialized the object itself, the code doesn't have to handle cultural differences in date and time formats. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/Persistence.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/Persistence.fs" id="Snippet4"::: - -The previous example doesn't include time information. If a value represents a moment in time and is expressed as a local time, convert it from local time to UTC before serializing it by calling the method. After you deserialize it, convert it from UTC to local time by calling the method. - -## DateTime vs. TimeSpan - -The and value types differ in that a represents an instant in time whereas a represents a time interval. You can subtract one instance of from another to obtain a object that represents the time interval between them. Or you could add a positive to the current to obtain a value that represents a future date. - -You can add or subtract a time interval from a object. Time intervals can be negative or positive, and they can be expressed in units such as ticks, seconds, or as a object. - -## Compare for equality within tolerance - -Equality comparisons for values are exact. To be considered equal, two values must be expressed as the same number of ticks. That precision is often unnecessary or even incorrect for many applications. Often, you want to test if objects are **roughly equal**. - -The following example demonstrates how to compare roughly equivalent values. It accepts a small margin of difference when declaring them equal. - - -:::code language="csharp" source="./snippets/System/DateTime/Overview/csharp/DateTimeComparisons.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/DateTime/Overview/fsharp/DateTimeComparisons.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/DateTime/Overview/vb/DateTimeComparisons.vb" id="Snippet1"::: - -## COM interop considerations - -A value that is transferred to a COM application, then is transferred back to a managed application, is said to round-trip. However, a value that specifies only a time does not round-trip as you might expect. - -If you round-trip only a time, such as 3 P.M., the final date and time is December 30, 1899 C.E. at 3:00 P.M., instead of January, 1, 0001 C.E. at 3:00 P.M. .NET and COM assume a default date when only a time is specified. However, the COM system assumes a base date of December 30, 1899 C.E., while .NET assumes a base date of January, 1, 0001 C.E. - -When only a time is passed from .NET to COM, special processing is performed that converts the time to the format used by COM. When only a time is passed from COM to .NET, no special processing is performed because that would corrupt legitimate dates and times on or before December 30, 1899. If a date starts its round-trip from COM, .NET and COM preserve the date. - -The behavior of .NET and COM means that if your application round-trips a that only specifies a time, your application must remember to modify or ignore the erroneous date from the final object. diff --git a/docs/fundamentals/runtime-libraries/system-decimal.md b/docs/fundamentals/runtime-libraries/system-decimal.md deleted file mode 100644 index a36913507d7f9..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-decimal.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: System.Decimal struct -description: Learn about the System.Decimal struct. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Decimal struct - -[!INCLUDE [context](includes/context.md)] - -The value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The default value of a `Decimal` is 0. The value type is appropriate for financial calculations that require large numbers of significant integral and fractional digits and no round-off errors. The type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding. For example, the following code produces a result of 0.9999999999999999999999999999 instead of 1. - -:::code language="csharp" source="./snippets/System/Decimal/Overview/csharp/DecimalDivision_46630_1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Decimal/Overview/fsharp/DecimalDivision_46630_1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Decimal/Overview/vb/DecimalDivision_46630_1.vb" id="Snippet1"::: - -When the result of the division and multiplication is passed to the method, the result suffers no loss of precision, as the following code shows. - -:::code language="csharp" source="./snippets/System/Decimal/Overview/csharp/DecimalDivision_46630_1.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Decimal/Overview/fsharp/DecimalDivision_46630_1.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Decimal/Overview/vb/DecimalDivision_46630_1.vb" id="Snippet2"::: - -A decimal number is a floating-point value that consists of a sign, a numeric value where each digit in the value ranges from 0 to 9, and a scaling factor that indicates the position of a floating decimal point that separates the integral and fractional parts of the numeric value. - -The binary representation of a `Decimal` value is 128-bits consisting of a 96-bit integer number, and a 32-bit set of flags representing things such as the sign and scaling factor used to specify what portion of it is a decimal fraction. Therefore, the binary representation of a value the form, ((-296 to 296) / 10(0 to 28)), where -(296-1) is equal to , and 296-1 is equal to . For more information about the binary representation of values and an example, see the constructor and the method. - -The scaling factor also preserves any trailing zeros in a number. Trailing zeros do not affect the value of a number in arithmetic or comparison operations. However, trailing zeros might be revealed by the method if an appropriate format string is applied. - -## Conversion considerations - -This type provides methods that convert values to and from , , , , , , , and values. Conversions from these integral types to are widening conversions that never lose information or throw exceptions. - -Conversions from to any of the integral types are narrowing conversions that round the value to the nearest integer value toward zero. Some languages, such as C#, also support the conversion of values to values. If the result of these conversions cannot be represented in the destination type, an exception is thrown. - -The type also provides methods that convert values to and from and values. Conversions from to or are narrowing conversions that might lose precision but not information about the magnitude of the converted value. The conversion does not throw an exception. - -Conversions from or to throw an exception if the result of the conversion cannot be represented as a . - -## Perform operations on Decimal values - -The type supports standard mathematical operations such as addition, subtraction, division, multiplication, and unary negation. You can also work directly with the binary representation of a value by calling the method. - -To compare two values, you can use the standard numeric comparison operators, or you can call the or method. - -You can also call the members of the class to perform a wide range of numeric operations, including getting the absolute value of a number, determining the maximum or minimum value of two values, getting the sign of a number, and rounding a number. - -## Examples - -The following code example demonstrates the use of . - -:::code language="csharp" source="./snippets/System/Decimal/Overview/csharp/source.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Decimal/Overview/fsharp/source.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Decimal/Overview/vb/source.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-delegate-createdelegate.md b/docs/fundamentals/runtime-libraries/system-delegate-createdelegate.md deleted file mode 100644 index bcbac4cdb30e3..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-delegate-createdelegate.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: System.Delegate.CreateDelegate methods -description: Learn about the System.Delegate.CreateDelegate methods. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Delegate.CreateDelegate methods - -[!INCLUDE [context](includes/context.md)] - -The methods create a delegate of a specified type. - -## method - -This method overload is equivalent to calling the method overload and specifying `true` for `throwOnBindFailure`. - -### Examples - -This section contains two code examples. The first example demonstrates the two kinds of delegates that can be created with this method overload: open over an instance method and open over a static method. - -The second code example demonstrates compatible parameter types and return types. - -#### Example 1 - -The following code example demonstrates the two ways a delegate can be created using this overload of the method. - -> [!NOTE] -> There are two overloads of the method that specify a but not a first argument; their functionality is the same except that one allows you to specify whether to throw on failure to bind, and the other always throws. This code example uses both overloads. - -The example declares a class `C` with a static method `M2` and an instance method `M1`, and two delegate types: `D1` takes an instance of `C` and a string, and `D2` takes a string. - -A second class named `Example` contains the code that creates the delegates. - -- A delegate of type `D1`, representing an open instance method, is created for the instance method `M1`. An instance must be passed when the delegate is invoked. -- A delegate of type `D2`, representing an open static method, is created for the static method `M2`. - -:::code language="csharp" source="./snippets/System/Delegate/CreateDelegate/csharp/openClosedOver.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Delegate/CreateDelegate/fsharp/openClosedOver.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Delegate/CreateDelegate/vb/openClosedOver.vb" id="Snippet1"::: - -#### Example 2 - -The following code example demonstrates compatibility of parameter types and return types. - -The code example defines a base class named `Base` and a class named `Derived` that derives from `Base`. The derived class has a `static` (`Shared` in Visual Basic) method named `MyMethod` with one parameter of type `Base` and a return type of `Derived`. The code example also defines a delegate named `Example` that has one parameter of type `Derived` and a return type of `Base`. - -The code example demonstrates that the delegate named `Example` can be used to represent the method `MyMethod`. The method can be bound to the delegate because: - -- The parameter type of the delegate (`Derived`) is more restrictive than the parameter type of `MyMethod` (`Base`), so that it is always safe to pass the argument of the delegate to `MyMethod`. -- The return type of `MyMethod` (`Derived`) is more restrictive than the parameter type of the delegate (`Base`), so that it is always safe to cast the return type of the method to the return type of the delegate. - -The code example produces no output. - -:::code language="csharp" source="./snippets/System/Delegate/CreateDelegate/csharp/source1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Delegate/CreateDelegate/fsharp/source1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Delegate/CreateDelegate/vb/source.vb" id="Snippet1"::: - -## and methods - -The functionality of these two overloads is the same except that one allows you to specify whether to throw on failure to bind, and the other always throws. - -The delegate type and the method must have compatible return types. That is, the return type of `method` must be assignable to the return type of `type`. - -`firstArgument`, the second parameter to these overloads, is the first argument of the method the delegate represents. If `firstArgument` is supplied, it is passed to `method` every time the delegate is invoked; `firstArgument` is said to be bound to the delegate, and the delegate is said to be closed over its first argument. If `method` is `static` (`Shared` in Visual Basic), the argument list supplied when invoking the delegate includes all parameters except the first; if `method` is an instance method, then `firstArgument` is passed to the hidden instance parameter (represented by `this` in C#, or by `Me` in Visual Basic). - -If `firstArgument` is supplied, the first parameter of `method` must be a reference type, and `firstArgument` must be compatible with that type. - -> [!IMPORTANT] -> If `method` is `static` (`Shared` in Visual Basic) and its first parameter is of type or , then `firstArgument` can be a value type. In this case `firstArgument` is automatically boxed. Automatic boxing does not occur for any other arguments, as it would in a C# or Visual Basic function call. - -If `firstArgument` is a null reference and `method` is an instance method, the result depends on the signatures of the delegate type `type` and of `method`: - -- If the signature of `type` explicitly includes the hidden first parameter of `method`, the delegate is said to represent an open instance method. When the delegate is invoked, the first argument in the argument list is passed to the hidden instance parameter of `method`. -- If the signatures of `method` and `type` match (that is, all parameter types are compatible), then the delegate is said to be closed over a null reference. Invoking the delegate is like calling an instance method on a null instance, which is not a particularly useful thing to do. - -If `firstArgument` is a null reference and `method` is static, the result depends on the signatures of the delegate type `type` and of `method`: - -- If the signature of `method` and `type` match (that is, all parameter types are compatible), the delegate is said to represent an open static method. This is the most common case for static methods. In this case, you can get slightly better performance by using the method overload. -- If the signature of `type` begins with the second parameter of `method` and the rest of the parameter types are compatible, then the delegate is said to be closed over a null reference. When the delegate is invoked, a null reference is passed to the first parameter of `method`. - -### Example - -The following code example shows all the methods a single delegate type can represent: closed over an instance method, open over an instance method, open over a static method, and closed over a static method. - -The code example defines two classes, `C` and `F`, and a delegate type `D` with one argument of type `C`. The classes have matching static and instance methods `M1`, `M3`, and `M4`, and class `C` also has an instance method `M2` that has no arguments. - -A third class named `Example` contains the code that creates the delegates. - -- Delegates are created for instance method `M1` of type `C` and type `F`; each is closed over an instance of the respective type. Method `M1` of type `C` displays the `ID` properties of the bound instance and of the argument. -- A delegate is created for method `M2` of type `C`. This is an open instance delegate, in which the argument of the delegate represents the hidden first argument on the instance method. The method has no other arguments. It is called as if it were a static method. -- Delegates are created for static method `M3` of type `C` and type `F`; these are open static delegates. -- Finally, delegates are created for static method `M4` of type `C` and type `F`; each method has the declaring type as its first argument, and an instance of the type is supplied, so the delegates are closed over their first arguments. Method `M4` of type `C` displays the `ID` properties of the bound instance and of the argument. - -:::code language="csharp" source="./snippets/System/Delegate/CreateDelegate/csharp/source.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Delegate/CreateDelegate/fsharp/source.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Delegate/CreateDelegate/vb/source1.vb" id="Snippet1"::: - -## Compatible parameter types and return type - -The parameter types and return type of a delegate created using this method overload must be compatible with the parameter types and return type of the method the delegate represents; the types do not have to match exactly. - -A parameter of a delegate is compatible with the corresponding parameter of a method if the type of the delegate parameter is more restrictive than the type of the method parameter, because this guarantees that an argument passed to the delegate can be passed safely to the method. - -Similarly, the return type of a delegate is compatible with the return type of a method if the return type of the method is more restrictive than the return type of the delegate, because this guarantees that the return value of the method can be cast safely to the return type of the delegate. - -For example, a delegate with a parameter of type and a return type of can represent a method with a parameter of type and a return value of type . - -## Determine the methods a delegate can represent - -Another useful way to think of the flexibility provided by the overload is that any given delegate can represent four different combinations of method signature and method kind (static versus instance). Consider a delegate type `D` with one argument of type `C`. The following describes the methods `D` can represent, ignoring the return type since it must match in all cases: - -- `D` can represent any instance method that has exactly one argument of type `C`, regardless of what type the instance method belongs to. When is called, `firstArgument` is an instance of the type `method` belongs to, and the resulting delegate is said to be closed over that instance. (Trivially, `D` can also be closed over a null reference if `firstArgument` is a null reference.) - -- `D` can represent an instance method of `C` that has no arguments. When is called, `firstArgument` is a null reference. The resulting delegate represents an open instance method, and an instance of `C` must be supplied each time it is invoked. - -- `D` can represent a static method that takes one argument of type `C`, and that method can belong to any type. When is called, `firstArgument` is a null reference. The resulting delegate represents an open static method, and an instance of `C` must be supplied each time it is invoked. - -- `D` can represent a static method that belongs to type `F` and has two arguments, of type `F` and type `C`. When is called, `firstArgument` is an instance of `F`. The resulting delegate represents a static method that is closed over that instance of `F`. Note that in the case where `F` and `C` are the same type, the static method has two arguments of that type. (In this case, `D` is closed over a null reference if `firstArgument` is a null reference.) diff --git a/docs/fundamentals/runtime-libraries/system-diagnostics-performancecountertype.md b/docs/fundamentals/runtime-libraries/system-diagnostics-performancecountertype.md deleted file mode 100644 index 2b3ba88e68cc3..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-diagnostics-performancecountertype.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: System.Diagnostics.PerformanceCounterType enumeration -description: Learn about the System.Diagnostics.PerformanceCounterType enumeration. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Diagnostics.PerformanceCounterType enumeration - -[!INCLUDE [context](includes/context.md)] - -The enumeration specifies performance counter types that map directly to native types. - -Some counter types represent raw data, while others represent calculated values that are based on one or more counter samples. The following categories classify the types of counters available. - -- **Average**: Measures a value over time and displays the average of the last two measurements. A base counter that tracks the number of samples involved is associated with each average counter. -- **Difference**: Subtracts the last measurement from the previous one and, if the difference is positive, displays it; if negative, displays a zero. -- **Instantaneous**: Displays the most recent measurement. -- **Percentage**: Displays calculated values as a percentage. -- **Rate**: Samples an increasing count of events over time and divides the change in count values by the change in time to display a rate of activity. - -When sampling performance counter data, using a counter type that represents an average can make raw data values meaningful for your use. For example, the raw data counter `NumberOfItems64` can expose data that is fairly random from sample to sample. The formula for an average calculation of the values that the counter returns would be (X 0 +X 1 +…+X n)/n, where each X i is a raw counter sample. - -Rate counters are similar to average counters, but more useful for situations in which the rate increases as a resource is used. A formula that quickly calculates the average is ((X n -X 0)/(T n -T 0)) / frequency, where each X i is a counter sample and each T i is the time that the corresponding sample was taken. The result is the average usage per second. - -*Multitimer counters* collect data from more than one instance of a component, such as a processor or disk. - -*Inverse counters* measure the time that a component is not active and derive the active time from that measurement. - -> [!NOTE] -> Unless otherwise indicated, the time base is seconds. - -When instrumenting applications (creating and writing custom performance counters), you might be working with performance counter types that rely on an accompanying base counter that is used in the calculations. The base counter must be immediately after its associated counter in the collection your application uses. The following table lists the base counter types with their corresponding performance counter types. - -| Base counter type | Performance counter types | -|--------------------|----------------------------------------------| -| `AverageBase` | `AverageTimer32`

`AverageCount64` | -| `RawBase` | `RawFraction` | -| `CounterMultiBase` | `CounterMultiTimer`

`CounterMultiTimerInverse`

`CounterMultiTimer100Ns`

`CounterMultiTimer100NsInverse`| -| `SampleBase` | `SampleFraction` | - -The following are the formulas used by some of the counters that represent calculated values: - -- `AverageCount64`: (N1 - N0)/(B1 - B0), where N 1 and N 0 are performance counter readings, and B1 and B0 are their corresponding `AverageBase` values. Thus, the numerator represents the numbers of items processed during the sample interval, and the denominator represents the number of operations completed during the sample interval. - -- `AverageTimer32`: ((N1 - N0)/F)/(B1 - B0), where N1 and N0 are performance counter readings, B1 and B0 are their corresponding `AverageBase` values, and F is the number of ticks per second. The value of F is factored into the equation so that the result can be displayed in seconds. Thus, the numerator represents the numbers of ticks counted during the last sample interval, F represents the frequency of the ticks, and the denominator represents the number of operations completed during the last sample interval. - -- `CounterDelta32`: N1 - N0, where N1 and N0 are performance counter readings. - -- `CounterDelta64`: N1 - N0, where N1 and N0 are performance counter readings. - -- `CounterMultiTimer`: ((N1 - N0) / (D1 - D0)) x 100 / B, where N1 and N0 are performance counter readings, D1 and D0 are their corresponding time readings in ticks of the system performance timer, and the variable B denotes the base count for the monitored components (using a base counter of type `CounterMultiBase`). Thus, the numerator represents the portions of the sample interval during which the monitored components were active, and the denominator represents the total elapsed time of the sample interval. - -- `CounterMultiTimer100Ns`: ((N1 - N0) / (D1 - D0)) x 100 / B, where N1 and N0 are performance counter readings, D1 and D0 are their corresponding time readings in 100-nanosecond units, and the variable B denotes the base count for the monitored components (using a base counter of type `CounterMultiBase`). Thus, the numerator represents the portions of the sample interval during which the monitored components were active, and the denominator represents the total elapsed time of the sample interval. - -- `CounterMultiTimer100NsInverse`: (B - ((N1 - N0) / (D1 - D0))) x 100, where the denominator represents the total elapsed time of the sample interval, the numerator represents the time during the interval when monitored components were inactive, and B represents the number of components being monitored, using a base counter of type `CounterMultiBase`. - -- `CounterMultiTimerInverse`: (B- ((N1 - N0) / (D1 - D0))) x 100, where the denominator represents the total elapsed time of the sample interval, the numerator represents the time during the interval when monitored components were inactive, and B represents the number of components being monitored, using a base counter of type `CounterMultiBase`. - -- `CounterTimer`: (N1 - N0) / (D1 - D0), where N1 and N0 are performance counter readings, and D1 and D0 are their corresponding time readings. Thus, the numerator represents the portions of the sample interval during which the monitored components were active, and the denominator represents the total elapsed time of the sample interval. - -- `CounterTimerInverse`: (1- ((N1 - N0) / (D1 - D0))) x 100, where the numerator represents the time during the interval when the monitored components were inactive, and the denominator represents the total elapsed time of the sample interval. - -- `CountPerTimeInterval32`: (N1 - N0) / (D1 - D0), where the numerator represents the number of items in the queue, and the denominator represents the time elapsed during the last sample interval. - -- `CountPerTimeInterval64`: (N1 - N0) / (D1 - D0), where the numerator represents the number of items in a queue and the denominator represents the time elapsed during the sample interval. - -- `ElapsedTime`: (D0 - N0) / F, where D0 represents the current time, N0 represents the time the object was started, and F represents the number of time units that elapse in one second. The value of F is factored into the equation so that the result can be displayed in seconds. - -- `NumberOfItems32`: None. Does not display an average, but shows the raw data as it is collected. - -- `NumberOfItems64`: None. Does not display an average, but shows the raw data as it is collected. - -- `NumberOfItemsHEX32`: None. Does not display an average, but shows the raw data as it is collected. - -- `NumberOfItemsHEX64`: None. Does not display an average, but shows the raw data as it is collected - -- `RateOfCountsPerSecond32`: (N1 - N0) / ((D1 - D0) / F), where N1 and N0 are performance counter readings, D1 and D0 are their corresponding time readings, and F represents the number of ticks per second. Thus, the numerator represents the number of operations performed during the last sample interval, the denominator represents the number of ticks elapsed during the last sample interval, and F is the frequency of the ticks. The value of F is factored into the equation so that the result can be displayed in seconds. - -- `RateOfCountsPerSecond64`: (N1 - N0) / ((D1 - D0) / F), where N1 and N0 are performance counter readings, D1 and D0 are their corresponding time readings, and F represents the number of ticks per second. Thus, the numerator represents the number of operations performed during the last sample interval, the denominator represents the number of ticks elapsed during the last sample interval, and F is the frequency of the ticks. The value of F is factored into the equation so that the result can be displayed in seconds. - -- `RawFraction`: (N0 / D0) x 100, where D0 represents a measured attribute (using a base counter of type `RawBase`) and N0 represents one component of that attribute. - -- `SampleCounter`: (N1 - N0) / ((D1 - D0) / F), where the numerator (N) represents the number of operations completed, the denominator (D) represents elapsed time in units of ticks of the system performance timer, and F represents the number of ticks that elapse in one second. F is factored into the equation so that the result can be displayed in seconds. - -- `SampleFraction`: ((N1 - N0) / (D1 - D0)) x 100, where the numerator represents the number of successful operations during the last sample interval, and the denominator represents the change in the number of all operations (of the type measured) completed during the sample interval, using counters of type `SampleBase`. - -- `Timer100Ns`: (N1 - N0) / (D1 - D0) x 100, where the numerator represents the portions of the sample interval during which the monitored components were active, and the denominator represents the total elapsed time of the sample interval. - -- `Timer100NsInverse`: (1- ((N1 - N0) / (D1 - D0))) x 100, where the numerator represents the time during the interval when the monitored components were inactive, and the denominator represents the total elapsed time of the sample interval. - -## Examples - -The following examples demonstrate several of the counter types in the enumeration. - -### AverageCount64 - -:::code language="csharp" source="./snippets/System.Diagnostics/CounterCreationData/Overview/csharp/averagecount32.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/vb/averagecount32.vb" id="Snippet1"::: - -### AverageTimer32 - -:::code language="csharp" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/csharp/averagetimer32.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/vb/averagetimer32.vb" id="Snippet2"::: - -### ElapsedTime - -:::code language="csharp" source="./snippets/System.Diagnostics/PerformanceCounter/NextValue/csharp/elapsedtime.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/vb/elapsedtime.vb" id="Snippet2"::: - -### NumberOfItems32 - -:::code language="csharp" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/csharp/numberofitems32.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/vb/numberofitems32.vb" id="Snippet1"::: - -### NumberOfItems64 - -:::code language="csharp" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/csharp/numberofitems64.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/vb/numberofitems64.vb" id="Snippet1"::: - -### SampleFraction - -:::code language="csharp" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/csharp/program.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/vb/program.vb" id="Snippet1"::: - -### RateOfCountsPerSecond32 - -:::code language="csharp" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/csharp/rateofcountspersecond32.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/vb/rateofcountspersecond32.vb" id="Snippet1"::: - -### RateOfCountsPerSecond64 - -:::code language="csharp" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/csharp/rateofcountspersecond64.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/vb/rateofcountspersecond64.vb" id="Snippet1"::: - -### RawFraction - -:::code language="csharp" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/csharp/rawfraction.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Diagnostics/PerformanceCounterType/Overview/vb/rawfraction.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-diagnostics-processstartinfo-useshellexecute.md b/docs/fundamentals/runtime-libraries/system-diagnostics-processstartinfo-useshellexecute.md deleted file mode 100644 index 9a0b5f8d1c096..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-diagnostics-processstartinfo-useshellexecute.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: System.Diagnostics.ProcessStartInfo.UseShellExecute property -description: Learn about the System.Diagnostics.ProcessStartInfo.UseShellExecute property. -ms.date: 01/24/2024 ---- -# System.Diagnostics.ProcessStartInfo.UseShellExecute property - -[!INCLUDE [context](includes/context.md)] - -The class specifies a set of values that are used when you start a process. - -Setting the property to `false` enables you to redirect input, output, and error streams. - -The word "shell" in this context (`UseShellExecute`) refers to a graphical shell (similar to the Windows shell) rather than command shells (for example, `bash` or `sh`) and lets users launch graphical applications or open documents. - -> [!NOTE] -> must be `false` if the property is not `null` or an empty string, or an will be thrown when the method is called. - -When you use the operating system shell to start processes, you can start any document (which is any registered file type associated with an executable that has a default open action) and perform operations on the file, such as printing, by using the object. When is `false`, you can start only executables by using the object. - -> [!NOTE] -> must be `true` if you set the property to `true`. - -## WorkingDirectory - -The property behaves differently depending on the value of the property. When is `true`, the property specifies the location of the executable. If is an empty string, it's assumed that the current directory contains the executable. - -When is `false`, the property is not used to find the executable. Instead, it is used only by the process that is started and has meaning only within the context of the new process. When is `false`, the property can be either a fully qualified path to the executable, or a simple executable name that the system will attempt to find within folders specified by the `PATH` environment variable. The interpretation of the search path depends on the operating system. For more information, enter [`HELP PATH`](/windows-server/administration/windows-commands/path) or [`man sh`](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03) at a command prompt. diff --git a/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md b/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md deleted file mode 100644 index 13a375f29f12e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventsource.md +++ /dev/null @@ -1,74 +0,0 @@ ---- -title: System.Diagnostics.Tracing.EventSource class -description: Learn about the System.Diagnostics.Tracing.EventSource class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Diagnostics.Tracing.EventSource class - -[!INCLUDE [context](includes/context.md)] - -The class is intended to be inherited by a user class that provides specific events to be used for event tracing. The methods are called to log the events. - -The basic functionality of is sufficient for most applications. If you want more control over the event metadata that's created, you can apply the attribute to the methods. For advanced event source applications, it is possible to intercept the commands being sent to the derived event source and change the filtering, or to cause actions (such as dumping a data structure) to be performed by the inheritor. An event source can be activated in-process using and out-of-process using EventPipe-based tools such as `dotnet-trace` or Event Tracing for Windows (ETW) based tools like `PerfView` or `Logman`. It is also possible to programmatically control and intercept the data dispatcher. The class provides additional functionality. - -## Conventions - --derived classes should follow the following conventions: - -- User-defined classes should implement a singleton pattern. The singleton instance is traditionally named `Log`. By extension, users should not call `IDisposable.Dispose` manually and allow the runtime to clean up the singleton instance at the end of managed code execution. -- A user-defined, derived class should be marked as `sealed` unless it implements the advanced "Utility EventSource" configuration discussed in the Advanced Usage section. -- Call before performing any resource intensive work related to firing an event. -- You can implicitly create objects by declaring two event methods with subsequent event IDs that have the naming pattern `Start` and `Stop`. These events _must_ be declared next to each other in the class definition and the `Start` method _must_ come first. -- Attempt to keep objects backwards compatible and version them appropriately. The default version for an event is `0`. The version can be can be changed by setting . Change the version of an event whenever you change properties of the payload. Always add new payload properties to the end of the event declaration. If this is not possible, create a new event with a new ID to replace the old one. -- When declaring event methods, specify fixed-size payload properties before variably sized properties. -- are used as a bit mask for specifying specific events when subscribing to a provider. You can specify keywords by defining a `public static class Keywords` member class that has `public const EventKeywords` members. -- Associate expensive events with an using . This pattern allows users of your to opt out of these expensive operations. - -## Self-describing (tracelogging) vs. manifest event formats - - can be configured into to two different modes based on the constructor used or what flags are set on . - -Historically, these two formats are derived from two formats that Event Tracing for Windows (ETW) used. While these two modes don't affect your ability to use Event Tracing for Windows (ETW) or EventPipe-based listeners, they do generate the metadata for events differently. - -The default event format is , which is set if not specified on . Manifest-based objects generate an XML document representing the events defined on the class upon initialization. This requires the to reflect over itself to generate the provider and event metadata. - -To use self-describing (tracelogging) event format, construct your using the constructor, the constructor, or by setting the `EtwSelfDescribingEventFormat` flag on . Self-describing sources generate minimal provider metadata on initialization and only generate event metadata when is called. Unlike the manifest-based format, when listening via ETW only the Level, Keyword, and Opcode metadata are included from the attribute. Other properties such as EventId or Message are not included. - -In practice, these event format settings only affect usage with readers based on Event Tracing for Windows (ETW). They can, however, have a small effect on initialization time and per-event write times due to the time required for reflection and generating the metadata. - -## Examples - -The following example shows a simple implementation of the class. - -:::code language="csharp" source="./snippets/System.Diagnostics.Tracing/EventSource/Overview/csharp/program.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Diagnostics.Tracing/EventSource/Overview/vb/program.vb" id="Snippet1"::: - -The following example shows a more complex implementation of the class. - -:::code language="csharp" source="./snippets/System.Diagnostics.Tracing/EventSource/Overview/csharp/program1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Diagnostics.Tracing/EventSource/Overview/vb/program1.vb" id="Snippet1"::: - -## Advanced usage - -Traditionally, user-defined objects expect to inherit directly from . For advanced scenarios, however, you can create `abstract` objects, called _Utility Sources_, and implement interfaces. Using one or both of these techniques allows you to share code between different derived sources. - -> [!IMPORTANT] -> Abstract objects cannot define keywords, tasks, opcodes, channels, or events. - -> [!IMPORTANT] -> To avoid name collisions at runtime when generating event metadata, don't explicitly implement interface methods when using interfaces with . - -The following example shows an implementation of that uses an interface. - -:::code language="csharp" source="./snippets/System.Diagnostics.Tracing/EventSource/Overview/csharp/program2.cs" id="InterfaceSource"::: - -The following example shows an implementation of that uses the Utility EventSource pattern. - -:::code language="csharp" source="./snippets/System.Diagnostics.Tracing/EventSource/Overview/csharp/program2.cs" id="UtilitySource"::: - -The following example shows an implementation of for tracing information about a component in a library. - -:::code language="csharp" source="./snippets/System.Diagnostics.Tracing/EventSource/Overview/csharp/program2.cs" id="ComplexSource"::: diff --git a/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventwritteneventargs.md b/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventwritteneventargs.md deleted file mode 100644 index bd552081af4dc..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-diagnostics-tracing-eventwritteneventargs.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: System.Diagnostics.Tracing.EventWrittenEventArgs class -description: Learn about the System.Diagnostics.Tracing.EventWrittenEventArgs class. -ms.date: 12/31/2023 ---- -# System.Diagnostics.Tracing.EventWrittenEventArgs class - -[!INCLUDE [context](includes/context.md)] - -The class provides data for the callback. - -Whenever an event is dispatched to an , the callback method is invoked. It is passed an `EventWrittenEventArgs` instance that contains information associated with the event. All property values of the `EventWrittenEventArgs` class are valid only during the callback. - -The following sections contain additional information about individual `EventWrittenEventArgs` properties. - -## ActivityId property - -When using and its derived classes, threads can be marked as having an activity associated with them. The `ActivityId` property returns the activity ID of the thread that logged the event. Note that threads do not have to have an activity, in which case this property returns . - -## OSThreadId and TimeStamp properties - -Starting with .NET Core 2.2, objects can subscribe to native runtime events (such as GC, JIT, and threadpool events) in addition to events emitted by objects. In previous versions of .NET Core and all versions of .NET Framework, the thread ID and timestamp can be gathered from the environment, because they are dispatched synchronously on the same thread that emitted them. Not all native runtime events can be dispatched synchronously, however. Some events, such as GC events, are emitted when managed thread execution is suspended. These events are buffered in native code and are dispatched by a dispatcher thread once managed code can execute again. Because these events are buffered, the environment cannot be used to reliably retrieve the thread ID and timestamp. Because of this, starting with .NET Core 2.2, thread ID and timestamp information are available as members of the `EventWrittenEventArgs` class. - -## RelatedActivityId property - -A related activity is an activity that is strongly related to the current one. Typically, it is either the activity that caused the current activity (events with the `Start` opcode typically do this) or an activity that was created by the current one (events with the `Send` opcode typically do this). When it is used, the `RelatedActivityID` is explicitly passed by the method doing the logging. Many events don't pass a `RelatedActivityId`, in which case this property returns . diff --git a/docs/fundamentals/runtime-libraries/system-double-compareto.md b/docs/fundamentals/runtime-libraries/system-double-compareto.md deleted file mode 100644 index 38e95286e1887..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-double-compareto.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: System.Double.CompareTo methods -description: Learn about the System.Double.CompareTo methods. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Double.CompareTo methods - -[!INCLUDE [context](includes/context.md)] - -## method - -Values must be identical to be considered equal. Particularly when floating-point values depend on multiple mathematical operations, it is common for them to lose precision and for their values to be nearly identical except for their least significant digits. Because of this, the return value of the method at times may seem surprising. For example, multiplication by a particular value followed by division by the same value should produce the original value. In the following example, however, the computed value turns out to be greater than the original value. Showing all significant digits of the two values by using the "R" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) indicates that the computed value differs from the original value in its least significant digits. For information on handling such comparisons, see the Remarks section of the method. - -:::code language="csharp" source="./snippets/System/Double/CompareTo/csharp/compareto2.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Double/CompareTo/fsharp/compareto2.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Double/CompareTo/vb/compareto2.vb" id="Snippet1"::: - -This method implements the interface and performs slightly better than the method because it does not have to convert the `value` parameter to an object. - -Note that, although an object whose value is is not considered equal to another object whose value is (even itself), the interface requires that `A.CompareTo(A)` return zero. - -## method - -The `value` parameter must be `null` or an instance of `Double`; otherwise, an exception is thrown. Any instance of , regardless of its value, is considered greater than `null`. - -Values must be identical to be considered equal. Particularly when floating-point values depend on multiple mathematical operations, it is common for them to lose precision and for their values to be nearly identical except for their least significant digits. Because of this, the return value of the method at times may seem surprising. For example, multiplication by a particular value followed by division by the same value should produce the original value. In the following example, however, the computed value turns out to be greater than the original value. Showing all significant digits of the two values by using the "R" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) indicates that the computed value differs from the original value in its least significant digits. For information on handling such comparisons, see the Remarks section of the method. - -:::code language="csharp" source="./snippets/System/Double/CompareTo/csharp/compareto3.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Double/CompareTo/fsharp/compareto3.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Double/CompareTo/vb/compareto3.vb" id="Snippet2"::: - -This method is implemented to support the interface. Note that, although a is not considered to be equal to another (even itself), the interface requires that `A.CompareTo(A)` return zero. - -## Widening conversions - -Depending on your programming language, it might be possible to code a method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. - -For example, suppose the instance type is and the parameter type is . The Microsoft C# compiler generates instructions to represent the value of the parameter as a object, then generates a method that compares the values of the instance and the widened representation of the parameter. - -Consult your programming language's documentation to determine if its compiler performs implicit widening conversions of numeric types. For more information, see the [Type Conversion Tables](../../standard/base-types/conversion-tables.md) topic. - -## Precision in comparisons - -The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of .NET. Consequently, a comparison of two particular numbers might change between versions of .NET because the precision of the numbers' internal representation might change. diff --git a/docs/fundamentals/runtime-libraries/system-double-epsilon.md b/docs/fundamentals/runtime-libraries/system-double-epsilon.md deleted file mode 100644 index 40c02f3b4f653..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-double-epsilon.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: System.Double.Epsilon property -description: Learn about the System.Double.Epsilon property. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Double.Epsilon property - -[!INCLUDE [context](includes/context.md)] - -The value of the property reflects the smallest positive value that is significant in numeric operations or comparisons when the value of the instance is zero. For example, the following code shows that zero and are considered to be unequal values, whereas zero and half the value of are considered to be equal. - -:::code language="csharp" source="./snippets/System/Double/Epsilon/csharp/epsilon.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/Double/Epsilon/fsharp/epsilon.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/Double/Epsilon/vb/epsilon.vb" id="Snippet5"::: - -More precisely, the floating point format consists of a sign, a 52-bit mantissa or significand, and an 11-bit exponent. As the following example shows, zero has an exponent of -1022 and a mantissa of 0. has an exponent of -1022 and a mantissa of 1. This means that is the smallest positive value greater than zero and represents the smallest possible value and the smallest possible increment for a whose exponent is -1022. - -:::code language="csharp" source="./snippets/System/Double/Epsilon/csharp/epsilon1.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System/Double/Epsilon/fsharp/epsilon1.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System/Double/Epsilon/vb/epsilon1.vb" id="Snippet6"::: - -However, the property is not a general measure of precision of the type; it applies only to instances that have a value of zero or an exponent of -1022. - -> [!NOTE] -> The value of the property is not equivalent to machine epsilon, which represents the upper bound of the relative error due to rounding in floating-point arithmetic. - -The value of this constant is 4.94065645841247e-324. - -Two apparently equivalent floating-point numbers might not compare equal because of differences in their least significant digits. For example, the C# expression, `(double)1/3 == (double)0.33333`, does not compare equal because the division operation on the left side has maximum precision while the constant on the right side is precise only to the specified digits. If you create a custom algorithm that determines whether two floating-point numbers can be considered equal, we do not recommend that you base your algorithm on the value of the constant to establish the acceptable absolute margin of difference for the two values to be considered equal. (Typically, that margin of difference is many times greater than .) For information about comparing two double-precision floating-point values, see and . - -## Platform notes - -On ARM systems, the value of the constant is too small to be detected, so it equates to zero. You can define an alternative epsilon value that equals 2.2250738585072014E-308 instead. diff --git a/docs/fundamentals/runtime-libraries/system-double-equals.md b/docs/fundamentals/runtime-libraries/system-double-equals.md deleted file mode 100644 index 9a277a3196598..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-double-equals.md +++ /dev/null @@ -1,54 +0,0 @@ ---- -title: System.Double.Equals method -description: Learn about the System.Double.Equals method. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Double.Equals method - -The method implements the interface, and performs slightly better than because it doesn't have to convert the `obj` parameter to an object. - -## Widening conversions - -Depending on your programming language, it might be possible to code a method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. - -For example, suppose the instance type is and the parameter type is . The Microsoft C# compiler generates instructions to represent the value of the parameter as a object, then generates a method that compares the values of the instance and the widened representation of the parameter. - -Consult your programming language's documentation to determine if its compiler performs implicit widening conversions of numeric types. For more information, see the [Type Conversion Tables](../../standard/base-types/conversion-tables.md) topic. - -## Precision in comparisons - -The method should be used with caution, because two apparently equivalent values can be unequal due to the differing precision of the two values. The following example reports that the value .333333 and the value returned by dividing 1 by 3 are unequal. - -:::code language="csharp" source="./snippets/System/Double/Epsilon/csharp/Equals_25051.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Double/Epsilon/fsharp/Equals_25051.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Double/Epsilon/vb/Equals_25051.vb" id="Snippet1"::: - -Rather than comparing for equality, one technique involves defining an acceptable relative margin of difference between two values (such as .001% of one of the values). If the absolute value of the difference between the two values is less than or equal to that margin, the difference is likely to be due to differences in precision and, therefore, the values are likely to be equal. The following example uses this technique to compare .33333 and 1/3, the two values that the previous code example found to be unequal. In this case, the values are equal. - -:::code language="csharp" source="./snippets/System/Double/Epsilon/csharp/Equals_25051.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Double/Epsilon/fsharp/Equals_25051.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Double/Epsilon/vb/Equals_25051.vb" id="Snippet2"::: - -> [!NOTE] -> Because defines the minimum expression of a positive value whose range is near zero, the margin of difference between two similar values must be greater than . Typically, it is many times greater than . Because of this, we recommend that you **don't** use when comparing values for equality. - -A second technique involves comparing the difference between two floating-point numbers with some absolute value. If the difference is less than or equal to that absolute value, the numbers are equal. If it's greater, the numbers are not equal. One alternative is to arbitrarily select an absolute value. That's problematic, however, because an acceptable margin of difference depends on the magnitude of the values. A second alternative takes advantage of a design feature of the floating-point format: The difference between the integer representation of two floating-point values indicates the number of possible floating-point values that separates them. For example, the difference between 0.0 and is 1, because is the smallest representable value when working with a whose value is zero. The following example uses this technique to compare .33333 and 1/3, which are the two values that the previous code example with the method found to be unequal. The example uses the method to convert a double-precision floating-point value to its integer representation. The example declares the values as equal if there are no possible floating-point values between their integer representations. - -:::code language="csharp" source="./snippets/System/Double/Equals/csharp/equalsabs1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Double/Equals/fsharp/equalsabs1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Double/Equals/vb/equalsabs1.vb" id="Snippet1"::: - -> [!NOTE] -> For some values, you might consider them equal even when there *is* a possible floating-point value between the integer representations. For example, consider the double values `0.39` and `1.69 - 1.3` (which is calculated as `0.3899999999999999`). On a little-endian computer, the integer representations of these values are `4600697235336603894` and `4600697235336603892`, respectively. The difference between the integer values is `2`, meaning there *is* a possible floating-point value between `0.39` and `1.69 - 1.3`. - -### Version differences - -The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of .NET. Consequently, a comparison of two particular numbers might change between versions of .NET because the precision of the numbers' internal representation might change. - -## NaN - -If two values are tested for equality by calling the method, the method returns `true`. However, if two values are tested for equality by using the *equality operator*, the operator returns `false`. When you want to determine whether the value of a is not a number (NaN), an alternative is to call the method. diff --git a/docs/fundamentals/runtime-libraries/system-double.md b/docs/fundamentals/runtime-libraries/system-double.md deleted file mode 100644 index 59e6028276f43..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-double.md +++ /dev/null @@ -1,214 +0,0 @@ ---- -title: System.Double struct -description: Learn about the System.Double struct. -ms.date: 04/07/2026 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Double struct - -[!INCLUDE [context](includes/context.md)] - -The value type represents a double-precision 64-bit number with values ranging from negative 1.79769313486232e308 to positive 1.79769313486232e308, as well as positive or negative zero, , , and not a number (). It's intended to represent values that are extremely large (such as distances between planets or galaxies) or extremely small (such as the molecular mass of a substance in kilograms) and that often are imprecise (such as the distance from earth to another solar system). The type complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic. - -## Floating-point representation and precision - -The data type stores double-precision floating-point values in a 64-bit binary format, as shown in the following table: - -| Part | Bits | -|-----------------------------------|-------| -| Significand or mantissa | 0-51 | -| Exponent | 52-62 | -| Sign (0 = Positive, 1 = Negative) | 63 | - -Just as decimal fractions are unable to precisely represent some fractional values (such as 1/3 or ), binary fractions are unable to represent some fractional values. For example, 1/10, which is represented precisely by .1 as a decimal fraction, is represented by .001100110011 as a binary fraction, with the pattern "0011" repeating to infinity. In this case, the floating-point value provides an imprecise representation of the number that it represents. Performing additional mathematical operations on the original floating-point value often tends to increase its lack of precision. For example, if you compare the result of multiplying .1 by 10 and adding .1 to .1 nine times, you see that addition, because it has involved eight more operations, has produced the less precise result. (Prior to .NET 10, this disparity is apparent only if you display the two values by using the "R" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md), which displays up to all 17 digits of precision supported by the type.) - -:::code language="csharp" source="./snippets/System/Double/Overview/csharp/representation1.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/representation1.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/Double/Overview/vb/representation1.vb" id="Snippet3"::: - -Because some numbers can't be represented exactly as fractional binary values, floating-point numbers can only approximate real numbers. - -All floating-point numbers also have a limited number of significant digits, which also determines how accurately a floating-point value approximates a real number. A value has up to 15 decimal digits of precision, although a maximum of 17 digits is maintained internally. This means that some floating-point operations might lack the precision to change a floating point value. The following example provides an illustration. It defines a very large floating-point value, and then adds the product of and one quadrillion to it. The product, however, is too small to modify the original floating-point value. Its least significant digit is thousandths, whereas the most significant digit in the product is 10-309. - -:::code language="csharp" source="./snippets/System/Double/Overview/csharp/representation2.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/representation2.fs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/Double/Overview/vb/representation2.vb" id="Snippet4"::: - -The limited precision of a floating-point number has several consequences: - -- Two floating-point numbers that appear equal for a particular precision might not compare equal, because their least significant digits are different. In the following example, a series of numbers are added together, and their total is compared with their expected total. - - :::code language="csharp" source="./snippets/System/Double/Overview/csharp/precisionlist3.cs" id="Snippet6"::: - :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/precisionlist3.fs" id="Snippet6"::: - :::code language="vb" source="./snippets/System/Double/Overview/vb/precisionlist3.vb" id="Snippet6"::: - - The two values are unequal because of a loss of precision during the addition operations. In this case, the issue can be resolved by calling the method to round the values to the desired precision before performing the comparison. - -- A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used, because the binary floating-point number might not equal the decimal number. A previous example illustrated this by displaying the result of multiplying .1 by 10 and adding .1 times. - - When accuracy in numeric operations with fractional values is important, you can use the type rather than the type. When accuracy in numeric operations with integral values beyond the range of the types is important, use the type. - -- A value might not *round-trip* if a floating-point number is involved. A value is said to round-trip if an operation converts an original floating-point number to another form, an inverse operation transforms the converted form back to a floating-point number, and the final floating-point number is equal to the original floating-point number. The round trip might fail because one or more least significant digits are lost or changed in the conversion. - - In the following example, three values are converted to strings and saved in a file. If you run this example on .NET Framework, even though the values appear to be identical, the restored values are not equal to the original values. (This has since been addressed in .NET, where the values round-trip correctly.) - - :::code language="csharp" source="./snippets/System/Double/Overview/csharp/precisionlist4.cs" id="Snippet7"::: - :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/precisionlist4.fs" id="Snippet7"::: - :::code language="vb" source="./snippets/System/Double/Overview/vb/precisionlist4.vb" id="Snippet7"::: - - If you're targeting .NET Framework, the values can be successfully round-tripped by using the "G17" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) to preserve the full precision of values. - -- values have less precision than values. A value that's converted to a seemingly equivalent often does not equal the value because of differences in precision. In the following example, the result of identical division operations is assigned to a and a value. After the value is cast to a , a comparison of the two values shows that they are unequal. - - :::code language="csharp" source="./snippets/System/Double/Overview/csharp/precisionlist1.cs" id="Snippet5"::: - :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/precisionlist1.fs" id="Snippet5"::: - :::code language="vb" source="./snippets/System/Double/Overview/vb/precisionlist1.vb" id="Snippet5"::: - - To avoid this problem, use either the in place of the data type, or use the method so that both values have the same precision. - -In addition, the result of arithmetic and assignment operations with values might differ slightly by platform because of the loss of precision of the type. For example, the result of assigning a literal value might differ in the 32-bit and 64-bit versions of .NET. The following example illustrates this difference when the literal value -4.42330604244772E-305 and a variable whose value is -4.42330604244772E-305 are assigned to a variable. Note that the result of the method in this case does not suffer from a loss of precision. - -:::code language="csharp" source="./snippets/System/Double/Overview/csharp/precision1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/precision1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Double/Overview/vb/precision1.vb" id="Snippet1"::: - -## Test for equality - -To be considered equal, two values must represent identical values. However, because of differences in precision between values, or because of a loss of precision by one or both values, floating-point values that are expected to be identical often turn out to be unequal because of differences in their least significant digits. As a result, calls to the method to determine whether two values are equal, or calls to the method to determine the relationship between two values, often yield unexpected results. This is evident in the following example, where two apparently equal values turn out to be unequal because the first has 15 digits of precision, while the second has 17. - -:::code language="csharp" source="./snippets/System/Double/Overview/csharp/comparison1.cs" id="Snippet9"::: -:::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/comparison1.fs" id="Snippet9"::: -:::code language="vb" source="./snippets/System/Double/Overview/vb/comparison1.vb" id="Snippet9"::: - -In cases where a loss of precision is likely to affect the result of a comparison, you can adopt any of the following alternatives to calling the or method: - -- Call the method to ensure that both values have the same precision. The following example modifies a previous example to use this approach so that two fractional values are equivalent. - - :::code language="csharp" source="./snippets/System/Double/Overview/csharp/comparison3.cs" id="Snippet11"::: - :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/comparison3.fs" id="Snippet11"::: - :::code language="vb" source="./snippets/System/Double/Overview/vb/comparison3.vb" id="Snippet11"::: - - The problem of precision still applies to rounding of midpoint values. For more information, see the method. - -- Test for approximate equality rather than equality. This requires that you define either an absolute amount by which the two values can differ but still be equal, or that you define a relative amount by which the smaller value can diverge from the larger value. - - > [!WARNING] - > is sometimes used as an absolute measure of the distance between two values when testing for equality. However, measures the smallest possible value that can be added to, or subtracted from, a whose value is zero. For most positive and negative values, the value of is too small to be detected. Therefore, except for values that are zero, we do not recommend its use in tests for equality. - - The following example uses the latter approach to define an `IsApproximatelyEqual` method that tests the relative difference between two values. The method divides by `Math.Max(value1, value2)` so the comparison is relative to the larger (by magnitude) of the two values, which places the result in the correct order of magnitude. If `Math.Max` returns zero (which happens when one value is zero and the other is negative), the method falls back to `Math.Min(value1, value2)` to use the non-zero value as the divisor. It also contrasts the result of calls to the `IsApproximatelyEqual` method and the method. - - :::code language="csharp" source="./snippets/System/Double/Overview/csharp/comparison4.cs" id="Snippet12"::: - :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/comparison4.fs" id="Snippet12"::: - :::code language="vb" source="./snippets/System/Double/Overview/vb/comparison4.vb" id="Snippet12"::: - -## Floating-point values and exceptions - -Unlike operations with integral types, which throw a for division by zero or an for overflow in a [checked context](../../csharp/language-reference/statements/checked-and-unchecked.md), operations with floating-point values don't throw exceptions. Instead, in exceptional situations, the result of a floating-point operation is zero, positive infinity, negative infinity, or not a number (NaN): - -- If the result of a floating-point operation is too small for the destination format, the result is zero. This can occur when two very small numbers are multiplied, as the following example shows. - - :::code language="csharp" source="./snippets/System/Double/Overview/csharp/exceptional1.cs" id="Snippet1"::: - :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/exceptional1.fs" id="Snippet1"::: - :::code language="vb" source="./snippets/System/Double/Overview/vb/exceptional1.vb" id="Snippet1"::: - -- If the magnitude of the result of a floating-point operation exceeds the range of the destination format, the result of the operation is or , as appropriate for the sign of the result. The result of an operation that overflows is , and the result of an operation that overflows is , as the following example shows. - - :::code language="csharp" source="./snippets/System/Double/Overview/csharp/exceptional2.cs" id="Snippet2"::: - :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/exceptional2.fs" id="Snippet2"::: - :::code language="vb" source="./snippets/System/Double/Overview/vb/exceptional2.vb" id="Snippet2"::: - - also results from a division by zero with a positive dividend, and results from a division by zero with a negative dividend. - -- If a floating-point operation is invalid, the result of the operation is . For example, results from the following operations: - - - Division by zero with a dividend of zero. Note that other cases of division by zero result in either or . - - - Any floating-point operation with an invalid input. For example, calling the method with a negative value returns , as does calling the method with a value that is greater than one or less than negative one. - - - Any operation with an argument whose value is . - -## Type conversions - -The structure does not define any explicit or implicit conversion operators; instead, conversions are implemented by the compiler. - -The conversion of the value of any primitive numeric type to a is a widening conversion and therefore does not require an explicit cast operator or call to a conversion method unless a compiler explicitly requires it. For example, the C# compiler requires a casting operator for conversions from to , while the Visual Basic compiler does not. The following example converts the minimum or maximum value of other primitive numeric types to a . - -:::code language="csharp" source="./snippets/System/Double/Overview/csharp/convert1.cs" id="Snippet20"::: -:::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/convert1.fs" id="Snippet20"::: -:::code language="vb" source="./snippets/System/Double/Overview/vb/convert1.vb" id="Snippet20"::: - -In addition, the values , , and convert to , , and , respectively. - -Note that the conversion of the value of some numeric types to a value can involve a loss of precision. As the example illustrates, a loss of precision is possible when converting , , and values to values. - -The conversion of a value to a value of any other primitive numeric data type is a narrowing conversion and requires a cast operator (in C#), a conversion method (in Visual Basic), or a call to a method. Values that are outside the range of the target data type, which are defined by the target type's `MinValue` and `MaxValue` properties, behave as shown in the following table. - -|Target type|Result| -|-----------------|------------| -|Any integral type|An exception if the conversion occurs in a checked context.

If the conversion occurs in an unchecked context (the default in C#), the conversion operation succeeds but the value overflows.| -||An exception.| -|| for negative values.

for positive values.| - -In addition, , , and throw an for conversions to integers in a checked context, but these values overflow when converted to integers in an unchecked context. For conversions to , they always throw an . For conversions to , they convert to , , and , respectively. - -A loss of precision might result from converting a value to another numeric type. In the case of converting to any of the integral types, as the output from the example shows, the fractional component is lost when the value is either rounded (as in Visual Basic) or truncated (as in C#). For conversions to and values, the value might not have a precise representation in the target data type. - -The following example converts a number of values to several other numeric types. The conversions occur in a checked context in Visual Basic (the default), in C# (because of the [checked](/dotnet/csharp/language-reference/keywords/checked) keyword), and in F# (because of the [Checked](https://fsharp.github.io/fsharp-core-docs/reference/fsharp-core-operators-checked.html) module). The output from the example shows the result for conversions in both a checked an unchecked context. You can perform conversions in an unchecked context in Visual Basic by compiling with the `/removeintchecks+` compiler switch, in C# by commenting out the `checked` statement, and in F# by commenting out the `open Checked` statement. - -:::code language="csharp" source="./snippets/System/Double/Overview/csharp/convert2.cs" id="Snippet21"::: -:::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/convert2.fs" id="Snippet21"::: -:::code language="vb" source="./snippets/System/Double/Overview/vb/convert2.vb" id="Snippet21"::: - -For more information on the conversion of numeric types, see [Type Conversion in .NET](../../standard/base-types/type-conversion.md) and [Type Conversion Tables](../../standard/base-types/conversion-tables.md). - -## Floating-point functionality - -The structure and related types provide methods to perform operations in the following areas: - -- **Comparison of values**. You can call the method to determine whether two values are equal, or the method to determine the relationship between two values. - - The structure also supports a complete set of comparison operators. For example, you can test for equality or inequality, or determine whether one value is greater than or equal to another. If one of the operands is a numeric type other than a , it is converted to a before performing the comparison. - - > [!WARNING] - > Because of differences in precision, two values that you expect to be equal might turn out to be unequal, which affects the result of the comparison. For information about comparing two values, see the [Test for equality](#test-for-equality) section. - - You can also call the , , , and methods to test for these special values. - -- **Mathematical operations**. Common arithmetic operations, such as addition, subtraction, multiplication, and division, are implemented by language compilers and Common Intermediate Language (CIL) instructions, rather than by methods. If one of the operands in a mathematical operation is a numeric type other than a , it's converted to a before performing the operation. The result of the operation is also a value. - - Other mathematical operations can be performed by calling `static` (`Shared` in Visual Basic) methods in the class. It includes additional methods commonly used for arithmetic (such as , , and ), geometry (such as and ), and calculus (such as ). - - You can also manipulate the individual bits in a value. The method preserves a value's bit pattern in a 64-bit integer. The method returns its bit pattern in a byte array. - -- **Rounding**. Rounding is often used as a technique for reducing the impact of differences between values caused by problems of floating-point representation and precision. You can round a value by calling the method. - -- **Formatting**. You can convert a value to its string representation by calling the method or by using the composite formatting feature. For information about how format strings control the string representation of floating-point values, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md). - -- **Parsing strings**. You can convert the string representation of a floating-point value to a value by calling either the or method. If the parse operation fails, the method throws an exception, whereas the method returns `false`. - -- **Type conversion**. The structure provides an explicit interface implementation for the interface, which supports conversion between any two standard .NET data types. Language compilers also support the implicit conversion of values of all other standard numeric types to values. Conversion of a value of any standard numeric type to a is a widening conversion and does not require the user of a casting operator or conversion method, - - However, conversion of and values can involve a loss of precision. The following table lists the differences in precision for each of these types: - - | Type | Maximum precision | Internal precision | - |----------------------|-------------------|--------------------| - | | 15 | 17 | - | | 19 decimal digits | 19 decimal digits | - | | 7 decimal digits | 9 decimal digits | - - The problem of precision most frequently affects values that are converted to values. In the following example, two values produced by identical division operations are unequal because one of the values is a single-precision floating point value converted to a . - - :::code language="csharp" source="./snippets/System/Double/Overview/csharp/representation1.cs" id="Snippet3"::: - :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/representation1.fs" id="Snippet3"::: - :::code language="vb" source="./snippets/System/Double/Overview/vb/representation1.vb" id="Snippet3"::: - -## Examples - -The following code example illustrates the use of : - -:::code language="csharp" source="./snippets/System/Double/Overview/csharp/source.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/source.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Double/Overview/vb/source.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-drawing-drawing2d-matrix.md b/docs/fundamentals/runtime-libraries/system-drawing-drawing2d-matrix.md deleted file mode 100644 index 3abd355367e26..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-drawing-drawing2d-matrix.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: System.Drawing.Drawing2D.Matrix class -description: Learn about the System.Drawing.Drawing2D.Matrix class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Drawing.Drawing2D.Matrix class - -[!INCLUDE [context](includes/context.md)] - -The class encapsulates a 3-by-3 affine matrix that represents a geometric transform. - -In GDI+, you can store an affine transformation in a object. Because the third column of a matrix that represents an affine transformation is always (0, 0, 1), you specify only the six numbers in the first two columns when you construct a object. The statement `Matrix myMatrix = new Matrix(0, 1, -1, 0, 3, 4)` constructs the matrix shown in the following figure. - -![Matrix.](./media/gdip-art10.gif) - -[!INCLUDE[System.Drawing.Common note](./includes/system-drawing-common.md)] - -## Composite transformations - -A composite transformation is a sequence of transformations, one followed by the other. Consider the matrices and transformations in the following list: - -| Matrix | Transformation | -|----------|-------------------------------------------| -| Matrix A | Rotate 90 degrees | -| Matrix B | Scale by a factor of 2 in the x direction | -| Matrix C | Translate 3 units in the y direction | - -If you start with the point (2, 1) - represented by the matrix [2 1 1] - and multiply by A, then B, then C, the point (2, 1) will undergo the three transformations in the order listed. - -`[2 1 1]ABC = [-2 5 1]` - -Rather than store the three parts of the composite transformation in three separate matrices, you can multiply A, B, and C together to get a single 3×3 matrix that stores the entire composite transformation. Suppose `ABC = D`. Then a point multiplied by D gives the same result as a point multiplied by A, then B, then C. - -`[2 1 1]D = [-2 5 1]` - -The following illustration shows the matrices A, B, C, and D. - -![Matrices A, B, C, and D](./media/gdip-art12.gif) - -The fact that the matrix of a composite transformation can be formed by multiplying the individual transformation matrices means that any sequence of affine transformations can be stored in a single object. - -> [!CAUTION] -> The order of a composite transformation is important. In general, rotate, then scale, then translate is not the same as scale, then rotate, then translate. Similarly, the order of matrix multiplication is important. In general, ABC is not the same as BAC. - -The class provides several methods for building a composite transformation: , , , , , and . The following example creates the matrix of a composite transformation that first rotates 30 degrees, then scales by a factor of 2 in the y direction, and then translates 5 units in the x direction: - -:::code language="csharp" source="./snippets/System.Drawing.Drawing2D/Matrix/Overview/csharp/Class1.cs" id="Snippet11"::: -:::code language="vb" source="./snippets/System.Drawing.Drawing2D/Matrix/Overview/vb/Class1.vb" id="Snippet11"::: diff --git a/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md b/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md deleted file mode 100644 index 0f66555d027f6..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-dynamic-expandoobject.md +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: System.Dynamic.ExpandoObject class -description: Learn about the System.Dynamic.ExpandoObject class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Dynamic.ExpandoObject class - -[!INCLUDE [context](includes/context.md)] - -The class enables you to add and delete members of its instances at runtime and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like `sampleObject.sampleMember` instead of more complex syntax like `sampleObject.GetAttribute("sampleMember")`. - -The `ExpandoObject` class implements the standard Dynamic Language Runtime (DLR) interface , which enables you to share instances of the `ExpandoObject` class between languages that support the DLR interoperability model. For example, you can create an instance of the `ExpandoObject` class in C# and then pass it to an IronPython function. For more information, see [Dynamic Language Runtime Overview](../../framework/reflection-and-codedom/dynamic-language-runtime-overview.md) and [Introducing the ExpandoObject](/archive/blogs/csharpfaq/dynamic-in-c-4-0-introducing-the-expandoobject). - -The `ExpandoObject` class is an implementation of the dynamic object concept that enables getting, setting, and invoking members. If you want to define types that have their own dynamic dispatch semantics, use the class. If you want to define how dynamic objects participate in the interoperability protocol and manage DLR fast dynamic dispatch caching, create your own implementation of the interface. - -## Create an instance - -In C#, to enable late binding for an instance of the `ExpandoObject` class, you must use the `dynamic` keyword. For more information, see [Using Type dynamic](/dotnet/csharp/programming-guide/types/using-type-dynamic). - -In Visual Basic, dynamic operations are supported by late binding. For more information, see [Early and Late Binding (Visual Basic)](../../visual-basic/programming-guide/language-features/early-late-binding/index.md). - -The following code example demonstrates how to create an instance of the `ExpandoObject` class. - -:::code language="csharp" source="./snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Dynamic/ExpandoObject/Overview/vb/module1.vb" id="Snippet1"::: - -## Add new members - -You can add properties, methods, and events to instances of the `ExpandoObject` class. - -The following code example demonstrates how to add a new property to an instance of the `ExpandoObject` class. - -:::code language="csharp" source="./snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Dynamic/ExpandoObject/Overview/vb/module1.vb" id="Snippet2"::: - -The methods represent lambda expressions that are stored as delegates, which can be invoked when they are needed. The following code example demonstrates how to add a method that increments a value of the dynamic property. - -:::code language="csharp" source="./snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Dynamic/ExpandoObject/Overview/vb/module1.vb" id="Snippet3"::: - -The following code example demonstrates how to add an event to an instance of the `ExpandoObject` class. - -```csharp -class Program -{ - static void Main(string[] args) - { - dynamic sampleObject = new ExpandoObject(); - - // Create a new event and initialize it with null. - sampleObject.sampleEvent = null; - - // Add an event handler. - sampleObject.sampleEvent += new EventHandler(SampleHandler); - - // Raise an event for testing purposes. - sampleObject.sampleEvent(sampleObject, new EventArgs()); - } - - // Event handler. - static void SampleHandler(object sender, EventArgs e) - { - Console.WriteLine("SampleHandler for {0} event", sender); - } -} -// This code example produces the following output: -// SampleHandler for System.Dynamic.ExpandoObject event. -``` - -```vb -Module Module1 - -Sub Main() - Dim sampleObject As Object = New ExpandoObject() - - ' Create a new event and initialize it with null. - sampleObject.sampleEvent = Nothing - - ' Add an event handler. - Dim handler As EventHandler = AddressOf SampleHandler - sampleObject.sampleEvent = - [Delegate].Combine(sampleObject.sampleEvent, handler) - - ' Raise an event for testing purposes. - sampleObject.sampleEvent.Invoke(sampleObject, New EventArgs()) - -End Sub - -' Event handler. -Sub SampleHandler(ByVal sender As Object, ByVal e As EventArgs) - Console.WriteLine("SampleHandler for {0} event", sender) -End Sub - -' This code example produces the following output: -' SampleHandler for System.Dynamic.ExpandoObject event. - -End Module -``` - -## Pass as a parameter - -You can pass instances of the `ExpandoObject` class as parameters. Note that these instances are treated as dynamic objects in C# and late-bound objects in Visual Basic. This means that you do not have IntelliSense for object members and you do not receive compiler errors when you call non-existent members. If you call a member that does not exist, an exception occurs. - -The following code example demonstrates how you can create and use a method to print the names and values of properties. - -:::code language="csharp" source="./snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs" id="Snippet4"::: -:::code language="vb" source="./snippets/System.Dynamic/ExpandoObject/Overview/vb/module1.vb" id="Snippet4"::: - -## Enumerate and delete members - -The `ExpandoObject` class implements the `IDictionary` interface. This enables enumeration of members added to the instance of the `ExpandoObject` class at runtime. This can be useful if you do not know at compile time what members an instance might have. - -The following code example shows how you can cast an instance of the `ExpandoObject` class to the interface and enumerate the instance's members. - -:::code language="csharp" source="./snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs" id="Snippet5"::: -:::code language="vb" source="./snippets/System.Dynamic/ExpandoObject/Overview/vb/module1.vb" id="Snippet5"::: - -In languages that do not have syntax for deleting members (such as C# and Visual Basic), you can delete a member by implicitly casting an instance of the `ExpandoObject` to the `IDictionary` interface and then deleting the member as a key/value pair. This is shown in the following example. - -:::code language="csharp" source="./snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs" id="Snippet6"::: -:::code language="vb" source="./snippets/System.Dynamic/ExpandoObject/Overview/vb/module1.vb" id="Snippet6"::: - -## Receive notifications of property changes - -The `ExpandoObject` class implements the interface and can raise a event when a member is added, deleted, or modified. This enables `ExpandoObject` class integration with Windows Presentation Foundation (WPF) data binding and other environments that require notification about changes in the object content. - -The following code example demonstrates how to create an event handler for the `PropertyChanged` event. - -:::code language="csharp" source="./snippets/System.Dynamic/ExpandoObject/Overview/csharp/program.cs" id="Snippet7"::: -:::code language="vb" source="./snippets/System.Dynamic/ExpandoObject/Overview/vb/module1.vb" id="Snippet7"::: diff --git a/docs/fundamentals/runtime-libraries/system-enum.md b/docs/fundamentals/runtime-libraries/system-enum.md deleted file mode 100644 index 8117cb3b75796..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-enum.md +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: System.Enum class -description: Learn about the System.Enum class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Enum class - -[!INCLUDE [context](includes/context.md)] - -An enumeration is a set of named constants whose underlying type is any integral type. If no underlying type is explicitly declared, is used. is the base class for all enumerations in .NET. Enumeration types are defined by the `enum` keyword in C#, the `Enum`...`End Enum` construct in Visual Basic, and the `type` keyword in F#. - - provides methods for comparing instances of this class, converting the value of an instance to its string representation, converting the string representation of a number to an instance of this class, and creating an instance of a specified enumeration and value. - -You can also treat an enumeration as a bit field. For more information, see the [Non-exclusive members and the Flags attribute](#non-exclusive-members-and-the-flags-attribute) section and . - -## Create an enumeration type - -Programming languages typically provide syntax to declare an enumeration that consists of a set of named constants and their values. The following example illustrates the syntax used by C#, F#, and Visual Basic to define an enumeration. It creates an enumeration named `ArrivalStatus` that has three members: `ArrivalStatus.Early`, `ArrivalStatus.OnTime`, and `ArrivalStatus.Late`. Note that in all cases, the enumeration does not explicitly inherit from ; the inheritance relationship is handled implicitly by the compiler. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/class1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/class1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/class1.vb" id="Snippet1"::: - -> [!WARNING] -> You should never create an enumeration type whose underlying type is non-integral or . Although you can create such an enumeration type by using reflection, method calls that use the resulting type are unreliable and may also throw additional exceptions. - -## Instantiate an enumeration type - -You can instantiate an enumeration type just as you instantiate any other value type: by declaring a variable and assigning one of the enumeration's constants to it. The following example instantiates an `ArrivalStatus` whose value is `ArrivalStatus.OnTime`. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/class1.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/class1.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/class1.vb" id="Snippet2"::: - -You can also instantiate an enumeration value in the following ways: - -- By using a particular programming language's features to cast (as in C#) or convert (as in Visual Basic) an integer value to an enumeration value. The following example creates an `ArrivalStatus` object whose value is `ArrivalStatus.Early` in this way. - - :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/class2.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/class2.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System/Enum/Overview/vb/class2.vb" id="Snippet4"::: - -- By calling its implicit parameterless constructor. As the following example shows, in this case the underlying value of the enumeration instance is 0. However, this is not necessarily the value of a valid constant in the enumeration. - - :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/class2.cs" id="Snippet3"::: - :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/class2.fs" id="Snippet3"::: - :::code language="vb" source="./snippets/System/Enum/Overview/vb/class2.vb" id="Snippet3"::: - -- By calling the or method to parse a string that contains the name of a constant in the enumeration. For more information, see the [Parse enumeration values](#parse-enumeration-values) section. - -- By calling the method to convert an integral value to an enumeration type. For more information, see the [Perform conversions](#perform-conversions) section. - -## Enumeration best practices - -We recommend that you use the following best practices when you define enumeration types: - -- If you have not defined an enumeration member whose value is 0, consider creating a `None` enumerated constant. By default, the memory used for the enumeration is initialized to zero by the common language runtime. Consequently, if you do not define a constant whose value is zero, the enumeration will contain an illegal value when it is created. - -- If there is an obvious default case that your application has to represent, consider using an enumerated constant whose value is zero to represent it. If there is no default case, consider using an enumerated constant whose value is zero to specify the case that is not represented by any of the other enumerated constants. - -- Do not specify enumerated constants that are reserved for future use. - -- When you define a method or property that takes an enumerated constant as a value, consider validating the value. The reason is that you can cast a numeric value to the enumeration type even if that numeric value is not defined in the enumeration. - -Additional best practices for enumeration types whose constants are bit fields are listed in the [Non-exclusive members and the Flags attribute](#non-exclusive-members-and-the-flags-attribute) section. - -## Perform operations with enumerations - -You cannot define new methods when you are creating an enumeration. However, an enumeration type inherits a complete set of static and instance methods from the class. The following sections survey most of these methods, in addition to several other methods that are commonly used when working with enumeration values. - -### Perform conversions - -You can convert between an enumeration member and its underlying type by using a casting (in C# and F#), or conversion (in Visual Basic) operator. In F#, the `enum` function is also used. The following example uses casting or conversion operators to perform conversions both from an integer to an enumeration value and from an enumeration value to an integer. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/class2.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/class2.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/class2.vb" id="Snippet5"::: - -The class also includes a method that converts a value of any integral type to an enumeration value. The following example uses the method to convert an to an `ArrivalStatus` value. Note that, because the returns a value of type , the use of a casting or conversion operator may still be necessary to cast the object to the enumeration type. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/class2.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/class2.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/class2.vb" id="Snippet6"::: - -When converting an integer to an enumeration value, it is possible to assign a value that is not actually a member of the enumeration. To prevent this, you can pass the integer to the method before performing the conversion. The following example uses this method to determine whether the elements in an array of integer values can be converted to `ArrivalStatus` values. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classconversion1.cs" id="Snippet7"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classconversion1.fs" id="Snippet7"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/classconversion1.vb" id="Snippet7"::: - -Although the class provides explicit interface implementations of the interface for converting from an enumeration value to an integral type, you should use the methods of the class, such as , to perform these conversions. The following example illustrates how you can use the method along with the method to convert an enumeration value to its underlying type. Note that this example does not require the underlying type of the enumeration to be known at compile time. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classconversion2.cs" id="Snippet8"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classconversion2.fs" id="Snippet8"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/classconversion2.vb" id="Snippet8"::: - -### Parse enumeration values - -The and methods allow you to convert the string representation of an enumeration value to that value. The string representation can be either the name or the underlying value of an enumeration constant. Note that the parsing methods will successfully convert string representations of numbers that are not members of a particular enumeration if the strings can be converted to a value of the enumeration's underlying type. To prevent this, the method can be called to ensure that the result of the parsing method is a valid enumeration value. The example illustrates this approach and demonstrates calls to both the and methods. Note that the non-generic parsing method returns an object that you may have to cast (in C# and F#) or convert (in Visual Basic) to the appropriate enumeration type. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classparse1.cs" id="Snippet9"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classparse1.fs" id="Snippet9"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/classparse1.vb" id="Snippet9"::: - -### Format enumeration values - -You can convert enumeration values to their string representations by calling the static method, as well as the overloads of the instance method. You can use a format string to control the precise way in which an enumeration value is represented as a string. For more information, see [Enumeration Format Strings](../../standard/base-types/enumeration-format-strings.md). The following example uses each of the supported enumeration format strings ("G" or "g", "D" or "d", "X" or "x", and "F" or "f" ) to convert a member of the `ArrivalStatus` enumeration to its string representations. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classformat1.cs" id="Snippet10"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classformat1.fs" id="Snippet10"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/classformat1.vb" id="Snippet10"::: - -### Iterate enumeration members - -The type does not implement the or interface, which would enable you to iterate members of a collection by using a `foreach` (in C#), `for..in` (in F#), or `For Each` (in Visual Basic) construct. However, you can enumerate members in either of two ways. - -- You can call the method to retrieve a string array containing the names of the enumeration members. Next, for each element of the string array, you can call the method to convert the string to its equivalent enumeration value. The following example illustrates this approach. - - :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classiterate.cs" id="Snippet11"::: - :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classiterate.fs" id="Snippet11"::: - :::code language="vb" source="./snippets/System/Enum/Overview/vb/classiterate.vb" id="Snippet11"::: - -- You can call the method to retrieve an array that contains the underlying values in the enumeration. Next, for each element of the array, you can call the method to convert the integer to its equivalent enumeration value. The following example illustrates this approach. - - :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classiterate.cs" id="Snippet12"::: - :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classiterate.fs" id="Snippet12"::: - :::code language="vb" source="./snippets/System/Enum/Overview/vb/classiterate.vb" id="Snippet12"::: - -## Non-exclusive members and the Flags attribute - -One common use of an enumeration is to represent a set of mutually exclusive values. For example, an `ArrivalStatus` instance can have a value of `Early`, `OnTime`, or `Late`. It makes no sense for the value of an `ArrivalStatus` instance to reflect more than one enumeration constant. - -In other cases, however, the value of an enumeration object can include multiple enumeration members, and each member represents a bit field in the enumeration value. The attribute can be used to indicate that the enumeration consists of bit fields. For example, an enumeration named `Pets` might be used to indicate the kinds of pets in a household. It can be defined as follows. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classbitwise1.cs" id="Snippet13"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classbitwise1.fs" id="Snippet13"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/classbitwise1.vb" id="Snippet13"::: - -The `Pets` enumeration can then be used as shown in the following example. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classbitwise1.cs" id="Snippet14"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classbitwise1.fs" id="Snippet14"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/classbitwise1.vb" id="Snippet14"::: - -The following best practices should be used when defining a bitwise enumeration and applying the attribute. - -- Use the custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value. - -- Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap. - -- Consider creating an enumerated constant for commonly used flag combinations. For example, if you have an enumeration used for file I/O operations that contains the enumerated constants `Read = 1` and `Write = 2`, consider creating the enumerated constant `ReadWrite = Read OR Write`, which combines the `Read` and `Write` flags. In addition, the bitwise OR operation used to combine the flags might be considered an advanced concept in some circumstances that should not be required for simple tasks. - -- Use caution if you define a negative number as a flag enumerated constant because many flag positions might be set to 1, which might make your code confusing and encourage coding errors. - -- A convenient way to test whether a flag is set in a numeric value is to call the instance method, as shown in the following example. - - :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classbitwise1.cs" id="Snippet15"::: - :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classbitwise1.fs" id="Snippet15"::: - :::code language="vb" source="./snippets/System/Enum/Overview/vb/classbitwise1.vb" id="Snippet15"::: - - It is equivalent to performing a bitwise AND operation between the numeric value and the flag enumerated constant, which sets all bits in the numeric value to zero that do not correspond to the flag, and then testing whether the result of that operation is equal to the flag enumerated constant. This is illustrated in the following example. - - :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classbitwise1.cs" id="Snippet16"::: - :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classbitwise1.fs" id="Snippet16"::: - :::code language="vb" source="./snippets/System/Enum/Overview/vb/classbitwise1.vb" id="Snippet16"::: - -- Use `None` as the name of the flag enumerated constant whose value is zero. You cannot use the `None` enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the `None` enumerated constant to determine whether any bits in the numeric value are set. This is illustrated in the following example. - - :::code language="csharp" source="./snippets/System/Enum/Overview/csharp/classbitwise1.cs" id="Snippet17"::: - :::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/classbitwise1.fs" id="Snippet17"::: - :::code language="vb" source="./snippets/System/Enum/Overview/vb/classbitwise1.vb" id="Snippet17"::: - -- Do not define an enumeration value solely to mirror the state of the enumeration itself. For example, do not define an enumerated constant that merely marks the end of the enumeration. If you need to determine the last value of the enumeration, check for that value explicitly. In addition, you can perform a range check for the first and last enumerated constant if all values within the range are valid. - -## Add enumeration methods - -Because enumeration types are defined by language structures, such as `enum` (C#), and `Enum` (Visual Basic), you cannot define custom methods for an enumeration type other than those methods inherited from the class. However, you can use extension methods to add functionality to a particular enumeration type. - -In the following example, the `Grades` enumeration represents the possible letter grades that a student may receive in a class. An extension method named `Passing` is added to the `Grades` type so that each instance of that type now "knows" whether it represents a passing grade or not. The `Extensions` class also contains a static read-write variable that defines the minimum passing grade. The return value of the `Passing` extension method reflects the current value of that variable. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/Extensions.cs" id="Snippet18"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/Extensions.fs" id="Snippet18"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/Extensions.vb" id="Snippet18"::: - -## Examples - -The following example demonstrates using an enumeration to represent named values and another enumeration to represent named bit fields. - -:::code language="csharp" source="./snippets/System/Enum/Overview/csharp/EnumMain.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Enum/Overview/fsharp/EnumMain.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Enum/Overview/vb/EnumMain.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-environment-getenvironmentvariable.md b/docs/fundamentals/runtime-libraries/system-environment-getenvironmentvariable.md deleted file mode 100644 index 1bc8477d3fbb9..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-environment-getenvironmentvariable.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: System.Environment.GetEnvironmentVariable methods -description: Learn about the System.Environment.GetEnvironmentVariable methods. -ms.date: 01/24/2024 ---- -# System.Environment.GetEnvironmentVariable methods - -[!INCLUDE [context](includes/context.md)] - -The method retrieves the value of an environment variable from the current process. - -Environment variable names are case-sensitive on Unix-like systems but aren't case-sensitive on Windows. - -> [!NOTE] -> In-process environment modifications made by native libraries aren't seen by managed callers. Conversely, such modifications made by managed callers aren't seen by native libraries. - -## method - -The method retrieves an environment variable from the environment block of the current process only. It's equivalent to calling the method with a `target` value of . - -To retrieve all environment variables along with their values, call the method. - -### On Windows systems - -On Windows systems, the environment block of the current process includes: - -- All environment variables that are provided to it by the parent process that created it. For example, a .NET application launched from a console window inherits all of the console window's environment variables. - - If there is no parent process, per-machine and per-user environment variables are used instead. For example, a new console window has all per-machine and per-user environment variables defined at the time it was launched. - -- Any variables added to the process block while the process is running by calling either the method or the method with a `target` value of . These environment variables persist until the .NET application terminates. - -If environment variables are created after the process has started, you can use this method to retrieve only those variables that were created by calling the method or the method with a `target` value of .. - -### On Unix-like systems - -On Unix-like systems, the environment block of the current process includes the following environment variables: - -- All environment variables that are provided to it by the parent process that created it. For .NET applications launched from a shell, this includes all environment variables defined in the shell. - -- Any variables added to the process block while the process is running by calling either the method or the method with a `target` value of . These environment variables persist until the .NET application terminates. - -.NET on Unix-like systems does not support per-machine or per-user environment variables. - -## method - -To retrieve all environment variables along with their values, call the method. - -### On Windows systems - -On Windows, the `target` parameter specifies whether the environment variable is retrieved from the current process or from the Windows operating system registry key for the current user or local machine. All per-user and per-machine environment variables are automatically copied into the environment block of the current process, as are any other environment variables that are available to the parent process that created the .NET process. However, environment variables added only to the environment block of the current process by calling either the method or the method with a `target` value of persist only for the duration of the process. - -### On Unix-like systems - -On Unix-like systems, the `GetEnvironmentVariable(String, EnvironmentVariableTarget)` method supports a `target` value of only. Calls with a `target` value of or are not supported and return `null`. - -Per-process environment variables are: - -- Those inherited from the parent process, typically the shell used to invoke `dotnet.exe` or to launch the .NET application. - -- Those defined by calling either the method or the method with a `target` value of . These environment variables persist only until the `dotnet` process or the .NET application terminates. diff --git a/docs/fundamentals/runtime-libraries/system-exception-data.md b/docs/fundamentals/runtime-libraries/system-exception-data.md deleted file mode 100644 index 20eec33718d81..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-exception-data.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: System.Exception.Data property -description: Learn about the System.Exception.Data property. -ms.date: 01/24/2024 ---- -# System.Exception.Data property - -[!INCLUDE [context](includes/context.md)] - -Use the object returned by the property to store and retrieve supplementary information relevant to the exception. The information is in the form of an arbitrary number of user-defined key/value pairs. The key component of each key/value pair is typically an identifying string, whereas the value component of the pair can be any type of object. - -## Key/value pair security - -The key/value pairs stored in the collection returned by the property are not secure. If your application calls a nested series of routines, and each routine contains exception handlers, the resulting call stack contains a hierarchy of those exception handlers. If a lower-level routine throws an exception, any upper-level exception handler in the call stack hierarchy can read and/or modify the key/value pairs stored in the collection by any other exception handler. This means you must guarantee that the information in the key/value pairs is not confidential and that your application will operate correctly if the information in the key/value pairs is corrupted. - -## Key conflicts - -A key conflict occurs when different exception handlers specify the same key to access a key/value pair. Use caution when developing your application because the consequence of a key conflict is that lower-level exception handlers can inadvertently communicate with higher-level exception handlers, and this communication might cause subtle program errors. However, if you are cautious you can use key conflicts to enhance your application. - -## Avoid key conflicts - -Avoid key conflicts by adopting a naming convention to generate unique keys for key/value pairs. For example, a naming convention might yield a key that consists of the period-delimited name of your application, the method that provides supplementary information for the pair, and a unique identifier. - -Suppose two applications, named Products and Suppliers, each has a method named Sales. The Sales method in the Products application provides the identification number (the stock keeping unit or SKU) of a product. The Sales method in the Suppliers application provides the identification number, or SID, of a supplier. Consequently, the naming convention for this example yields the keys, "Products.Sales.SKU" and "Suppliers.Sales.SID". - -## Exploit key conflicts - -Exploit key conflicts by using the presence of one or more special, prearranged keys to control processing. Suppose, in one scenario, the highest level exception handler in the call stack hierarchy catches all exceptions thrown by lower-level exception handlers. If a key/value pair with a special key exists, the high-level exception handler formats the remaining key/value pairs in the object in some nonstandard way; otherwise, the remaining key/value pairs are formatted in some normal manner. - -Now suppose, in another scenario, the exception handler at each level of the call stack hierarchy catches the exception thrown by the next lower-level exception handler. In addition, each exception handler knows the collection returned by the property contains a set of key/value pairs that can be accessed with a prearranged set of keys. - -Each exception handler uses the prearranged set of keys to update the value component of the corresponding key/value pair with information unique to that exception handler. After the update process is complete, the exception handler throws the exception to the next higher-level exception handler. Finally, the highest level exception handler accesses the key/value pairs and displays the consolidated update information from all the lower-level exception handlers. diff --git a/docs/fundamentals/runtime-libraries/system-exception-message.md b/docs/fundamentals/runtime-libraries/system-exception-message.md deleted file mode 100644 index bb4ff69c53d43..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-exception-message.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: System.Exception.Message property -description: Learn about the System.Exception.Message property. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Exception.Message property - -[!INCLUDE [context](includes/context.md)] - -Error messages target the developer who is handling the exception. The text of the property should completely describe the error and, when possible, should also explain how to correct the error. Top-level exception handlers may display the message to end-users, so you should ensure that it is grammatically correct and that each sentence of the message ends with a period. Do not use question marks or exclamation points. If your application uses localized exception messages, you should ensure that they are accurately translated. - -> [!IMPORTANT] -> Do not disclose sensitive information in exception messages without checking for the appropriate permissions. - -The value of the property is included in the information returned by . The property is set only when creating an . If no message was supplied to the constructor for the current instance, the system supplies a default message that is formatted using the current system culture. - -## Examples - -The following code example throws and then catches an exception and displays the exception's text message using the property. - -:::code language="csharp" source="./snippets/System/Exception/HelpLink/csharp/properties.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Exception/HelpLink/fsharp/properties.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Exception/HelpLink/vb/properties.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-exception.md b/docs/fundamentals/runtime-libraries/system-exception.md deleted file mode 100644 index 56762b8b7b157..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-exception.md +++ /dev/null @@ -1,230 +0,0 @@ ---- -title: System.Exception class -description: Learn about the System.Exception class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB - - FSharp ---- -# System.Exception class - -[!INCLUDE [context](includes/context.md)] - -The class is the base class for all exceptions. When an error occurs, either the system or the currently executing application reports it by throwing an exception that contains information about the error. After an exception is thrown, it is handled by the application or by the default exception handler. - -## Errors and exceptions - -Runtime errors can occur for a variety of reasons. However, not all errors should be handled as exceptions in your code. Here are some categories of errors that can occur at runtime and the appropriate ways to respond to them. - -- **Usage errors.** A usage error represents an error in program logic that can result in an exception. However, the error should be addressed not through exception handling but by modifying the faulty code. For example, the override of the method in the following example assumes that the `obj` argument must always be non-null. - - :::code language="csharp" source="./snippets/System/Exception/Overview/csharp/usageerrors1.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/usageerrors1.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System/Exception/Overview/vb/usageerrors1.vb" id="Snippet4"::: - - The exception that results when `obj` is `null` can be eliminated by modifying the source code to explicitly test for null before calling the override and then re-compiling. The following example contains the corrected source code that handles a `null` argument. - - :::code language="csharp" source="./snippets/System/Exception/Overview/csharp/usageerrors2.cs" id="Snippet5"::: - :::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/usageerrors2.fs" id="Snippet5"::: - :::code language="vb" source="./snippets/System/Exception/Overview/vb/usageerrors2.vb" id="Snippet5"::: - - Instead of using exception handling for usage errors, you can use the method to identify usage errors in debug builds, and the method to identify usage errors in both debug and release builds. For more information, see [Assertions in Managed Code](/visualstudio/debugger/assertions-in-managed-code). - -- **Program errors.** A program error is a runtime error that cannot necessarily be avoided by writing bug-free code. - - In some cases, a program error may reflect an expected or routine error condition. In this case, you may want to avoid using exception handling to deal with the program error and instead retry the operation. For example, if the user is expected to input a date in a particular format, you can parse the date string by calling the method, which returns a value that indicates whether the parse operation succeeded, instead of using the method, which throws a exception if the date string cannot be converted to a value. Similarly, if a user tries to open a file that does not exist, you can first call the method to check whether the file exists and, if it does not, prompt the user whether they want to create it. - - In other cases, a program error reflects an unexpected error condition that can be handled in your code. For example, even if you've checked to ensure that a file exists, it may be deleted before you can open it, or it may be corrupted. In that case, trying to open the file by instantiating a object or calling the method may throw a exception. In these cases, you should use exception handling to recover from the error. - -- **System failures.** A system failure is a runtime error that cannot be handled programmatically in a meaningful way. For example, any method can throw an exception if the common language runtime is unable to allocate additional memory. Ordinarily, system failures are not handled by using exception handling. Instead, you may be able to use an event such as and call the method to log exception information and notify the user of the failure before the application terminates. - -## Try/catch blocks - -The common language runtime provides an exception handling model that is based on the representation of exceptions as objects, and the separation of program code and exception handling code into `try` blocks and `catch` blocks. There can be one or more `catch` blocks, each designed to handle a particular type of exception, or one block designed to catch a more specific exception than another block. - -If an application handles exceptions that occur during the execution of a block of application code, the code must be placed within a `try` statement and is called a `try` block. Application code that handles exceptions thrown by a `try` block is placed within a `catch` statement and is called a `catch` block. Zero or more `catch` blocks are associated with a `try` block, and each `catch` block includes a type filter that determines the types of exceptions it handles. - -When an exception occurs in a `try` block, the system searches the associated `catch` blocks in the order they appear in application code, until it locates a `catch` block that handles the exception. A `catch` block handles an exception of type `T` if the type filter of the catch block specifies `T` or any type that `T` derives from. The system stops searching after it finds the first `catch` block that handles the exception. For this reason, in application code, a `catch` block that handles a type must be specified before a `catch` block that handles its base types, as demonstrated in the example that follows this section. A catch block that handles `System.Exception` is specified last. - -If none of the `catch` blocks associated with the current `try` block handle the exception, and the current `try` block is nested within other `try` blocks in the current call, the `catch` blocks associated with the next enclosing `try` block are searched. If no `catch` block for the exception is found, the system searches previous nesting levels in the current call. If no `catch` block for the exception is found in the current call, the exception is passed up the call stack, and the previous stack frame is searched for a `catch` block that handles the exception. The search of the call stack continues until the exception is handled or until no more frames exist on the call stack. If the top of the call stack is reached without finding a `catch` block that handles the exception, the default exception handler handles it and the application terminates. - -### F# try..with expression - -F# does not use `catch` blocks. Instead, a raised exception is pattern matched using a single `with` block. As this is an expression, rather than a statement, all paths must return the same type. To learn more, see [The try...with Expression](../../fsharp/language-reference/exception-handling/the-try-with-expression.md). - -## Exception type features - -Exception types support the following features: - -- Human-readable text that describes the error. When an exception occurs, the runtime makes a text message available to inform the user of the nature of the error and to suggest action to resolve the problem. This text message is held in the property of the exception object. During the creation of the exception object, you can pass a text string to the constructor to describe the details of that particular exception. If no error message argument is supplied to the constructor, the default error message is used. For more information, see the property. - -- The state of the call stack when the exception was thrown. The property carries a stack trace that can be used to determine where the error occurs in the code. The stack trace lists all the called methods and the line numbers in the source file where the calls are made. - -## Exception class properties - -The class includes a number of properties that help identify the code location, the type, the help file, and the reason for the exception: , , , , , , , and . - -When a causal relationship exists between two or more exceptions, the property maintains this information. The outer exception is thrown in response to this inner exception. The code that handles the outer exception can use the information from the earlier inner exception to handle the error more appropriately. Supplementary information about the exception can be stored as a collection of key/value pairs in the property. - -The error message string that is passed to the constructor during the creation of the exception object should be localized and can be supplied from a resource file by using the class. For more information about localized resources, see the [Creating Satellite Assemblies](/dotnet/framework/resources/creating-satellite-assemblies-for-desktop-apps) and [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps) topics. - -To provide the user with extensive information about why the exception occurred, the property can hold a URL (or URN) to a help file. - -The class uses the HRESULT `COR_E_EXCEPTION`, which has the value 0x80131500. - -For a list of initial property values for an instance of the class, see the constructors. - -## Performance considerations - -Throwing or handling an exception consumes a significant amount of system resources and execution time. Throw exceptions only to handle truly extraordinary conditions, not to handle predictable events or flow control. For example, in some cases, such as when you're developing a class library, it's reasonable to throw an exception if a method argument is invalid, because you expect your method to be called with valid parameters. An invalid method argument, if it is not the result of a usage error, means that something extraordinary has occurred. Conversely, do not throw an exception if user input is invalid, because you can expect users to occasionally enter invalid data. Instead, provide a retry mechanism so users can enter valid input. Nor should you use exceptions to handle usage errors. Instead, use [assertions](/visualstudio/debugger/assertions-in-managed-code) to identify and correct usage errors. - -In addition, do not throw an exception when a return code is sufficient; do not convert a return code to an exception; and do not routinely catch an exception, ignore it, and then continue processing. - -## Re-throw an exception - -In many cases, an exception handler simply wants to pass the exception on to the caller. This most often occurs in: - -- A class library that in turn wraps calls to methods in the .NET class library or other class libraries. - -- An application or library that encounters a fatal exception. The exception handler can log the exception and then re-throw the exception. - -The recommended way to re-throw an exception is to simply use the [throw](/dotnet/csharp/language-reference/keywords/throw) statement in C#, the [reraise](../../fsharp/language-reference/exception-handling/the-raise-function.md#reraising-an-exception) function in F#, and the [Throw](../../visual-basic/language-reference/statements/throw-statement.md) statement in Visual Basic without including an expression. This ensures that all call stack information is preserved when the exception is propagated to the caller. The following example illustrates this. A string extension method, `FindOccurrences`, wraps one or more calls to without validating its arguments beforehand. - -:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/rethrow1.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/rethrow1.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System/Exception/Overview/vb/rethrow1.vb" id="Snippet6"::: - -A caller then calls `FindOccurrences` twice. In the second call to `FindOccurrences`, the caller passes a `null` as the search string, which causes the method to throw an exception. This exception is handled by the `FindOccurrences` method and passed back to the caller. Because the throw statement is used with no expression, the output from the example shows that the call stack is preserved. - -:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/rethrow1.cs" id="Snippet7"::: -:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/rethrow1.fs" id="Snippet7"::: -:::code language="vb" source="./snippets/System/Exception/Overview/vb/rethrow1.vb" id="Snippet7"::: - -In contrast, if the exception is re-thrown by using this statement: - -```csharp -throw e; -``` - -```vb -Throw e -``` - -```fsharp -raise e -``` - -...then the full call stack is not preserved, and the example would generate the following output: - -```output -'a' occurs at the following character positions: 4, 7, 15 - -An exception (ArgumentNullException) occurred. -Message: - Value cannot be null. -Parameter name: value - -Stack Trace: - at Library.FindOccurrences(String s, String f) - at Example.Main() -``` - -A slightly more cumbersome alternative is to throw a new exception, and to preserve the original exception's call stack information in an inner exception. The caller can then use the new exception's property to retrieve stack frame and other information about the original exception. In this case, the throw statement is: - -:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/rethrow3.cs" id="Snippet8"::: -:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/rethrow3.fs" id="Snippet8"::: -:::code language="vb" source="./snippets/System/Exception/Overview/vb/rethrow3.vb" id="Snippet8"::: - -The user code that handles the exception has to know that the property contains information about the original exception, as the following exception handler illustrates. - -:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/rethrow3.cs" id="Snippet9"::: -:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/rethrow3.fs" id="Snippet9"::: -:::code language="vb" source="./snippets/System/Exception/Overview/vb/rethrow3.vb" id="Snippet9"::: - -## Choose standard exceptions - -When you have to throw an exception, you can often use an existing exception type in .NET instead of implementing a custom exception. You should use a standard exception type under these two conditions: - -- You're throwing an exception that is caused by a usage error (that is, by an error in program logic made by the developer who is calling your method). Typically, you would throw an exception such as , , , or . The string you supply to the exception object's constructor when instantiating the exception object should describe the error so that the developer can fix it. For more information, see the property. - -- You're handling an error that can be communicated to the caller with an existing .NET exception. You should throw the most derived exception possible. For example, if a method requires an argument to be a valid member of an enumeration type, you should throw an (the most derived class) rather than an . - -The following table lists common exception types and the conditions under which you would throw them. - -|Exception|Condition| -|---------------|---------------| -||A non-null argument that is passed to a method is invalid.| -||An argument that is passed to a method is `null`.| -||An argument is outside the range of valid values.| -||Part of a directory path is not valid.| -||The denominator in an integer or division operation is zero.| -||A drive is unavailable or does not exist.| -||A file does not exist.| -||A value is not in an appropriate format to be converted from a string by a conversion method such as `Parse`.| -||An index is outside the bounds of an array or collection.| -||A method call is invalid in an object's current state.| -||The specified key for accessing a member in a collection cannot be found.| -||A method or operation is not implemented.| -||A method or operation is not supported.| -||An operation is performed on an object that has been disposed.| -||An arithmetic, casting, or conversion operation results in an overflow.| -||A path or file name exceeds the maximum system-defined length.| -||The operation is not supported on the current platform.| -||An array with the wrong number of dimensions is passed to a method.| -||The time interval allotted to an operation has expired.| -||An invalid Uniform Resource Identifier (URI) is used.| - -## Implement custom exceptions - -In the following cases, using an existing .NET exception to handle an error condition is not adequate: - -- When the exception reflects a unique program error that cannot be mapped to an existing .NET exception. - -- When the exception requires handling that is different from the handling that is appropriate for an existing .NET exception, or the exception must be disambiguated from a similar exception. For example, if you throw an exception when parsing the numeric representation of a string that is out of range of the target integral type, you would not want to use the same exception for an error that results from the caller not supplying the appropriate constrained values when calling the method. - -The class is the base class of all exceptions in .NET. Many derived classes rely on the inherited behavior of the members of the class; they do not override the members of , nor do they define any unique members. - -To define your own exception class: - -1. Define a class that inherits from . If necessary, define any unique members needed by your class to provide additional information about the exception. For example, the class includes a property that specifies the name of the parameter whose argument caused the exception, and the property includes a property that indicates the time-out interval. - -2. If necessary, override any inherited members whose functionality you want to change or modify. Note that most existing derived classes of do not override the behavior of inherited members. - -3. Determine whether your custom exception object is serializable. Serialization enables you to save information about the exception and permits exception information to be shared by a server and a client proxy in a remoting context. To make the exception object serializable, mark it with the attribute. - -4. Define the constructors of your exception class. Typically, exception classes have one or more of the following constructors: - - - , which uses default values to initialize the properties of a new exception object. - - - , which initializes a new exception object with a specified error message. - - - , which initializes a new exception object with a specified error message and inner exception. - - - , which is a `protected` constructor that initializes a new exception object from serialized data. You should implement this constructor if you've chosen to make your exception object serializable. - -The following example illustrates the use of a custom exception class. It defines a `NotPrimeException` exception that is thrown when a client tries to retrieve a sequence of prime numbers by specifying a starting number that is not prime. The exception defines a new property, `NonPrime`, that returns the non-prime number that caused the exception. Besides implementing a protected parameterless constructor and a constructor with and parameters for serialization, the `NotPrimeException` class defines three additional constructors to support the `NonPrime` property. Each constructor calls a base class constructor in addition to preserving the value of the non-prime number. The `NotPrimeException` class is also marked with the attribute. - -:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/notprimeexception.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/notprimeexception.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Exception/Overview/vb/notprimeexception.vb" id="Snippet1"::: - -The `PrimeNumberGenerator` class shown in the following example uses the Sieve of Eratosthenes to calculate the sequence of prime numbers from 2 to a limit specified by the client in the call to its class constructor. The `GetPrimesFrom` method returns all prime numbers that are greater than or equal to a specified lower limit, but throws a `NotPrimeException` if that lower limit is not a prime number. - -:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/primenumbergenerator.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/primenumbergenerator.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Exception/Overview/vb/primenumbergenerator.vb" id="Snippet2"::: - -The following example makes two calls to the `GetPrimesFrom` method with non-prime numbers, one of which crosses application domain boundaries. In both cases, the exception is thrown and successfully handled in client code. - -:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/example.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/example.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/Exception/Overview/vb/example.vb" id="Snippet3"::: - -## Examples - -The following example demonstrates a `catch` (`with` in F#) block that is defined to handle errors. This `catch` block also catches errors, because derives from and there is no `catch` block explicitly defined for errors. - -:::code language="csharp" source="./snippets/System/Exception/Overview/csharp/catchexception.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Exception/Overview/fsharp/catchexception.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Exception/Overview/vb/catchexception.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-flagsattribute.md b/docs/fundamentals/runtime-libraries/system-flagsattribute.md deleted file mode 100644 index 7c8a7172d6f93..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-flagsattribute.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: System.FlagsAttribute class -description: Learn about the System.FlagsAttribute class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.FlagsAttribute class - -[!INCLUDE [context](includes/context.md)] - -The attribute indicates that an enumeration can be treated as a bit field; that is, a set of flags. - -Bit fields are generally used for lists of elements that might occur in combination, whereas enumeration constants are generally used for lists of mutually exclusive elements. Therefore, bit fields are designed to be combined with a bitwise `OR` operation to generate unnamed values, whereas enumerated constants are not. Languages vary in their use of bit fields compared to enumeration constants. - -## Attributes of the FlagsAttribute - - is applied to this class, and its property specifies `false`. This attribute can only be applied to enumerations. - -## Guidelines for FlagsAttribute and enum - -- Use the custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value. - -- Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap. - -- Consider creating an enumerated constant for commonly used flag combinations. For example, if you have an enumeration used for file I/O operations that contains the enumerated constants `Read = 1` and `Write = 2`, consider creating the enumerated constant `ReadWrite = Read OR Write`, which combines the `Read` and `Write` flags. In addition, the bitwise OR operation used to combine the flags might be considered an advanced concept in some circumstances that should not be required for simple tasks. - -- Use caution if you define a negative number as a flag enumerated constant because many flag positions might be set to 1, which might make your code confusing and encourage coding errors. - -- A convenient way to test whether a flag is set in a numeric value is to perform a bitwise AND operation between the numeric value and the flag enumerated constant, which sets all bits in the numeric value to zero that do not correspond to the flag, then test whether the result of that operation is equal to the flag enumerated constant. - -- Use `None` as the name of the flag enumerated constant whose value is zero. You cannot use the `None` enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the `None` enumerated constant to determine whether any bits in the numeric value are set. - - If you create a value enumeration instead of a flags enumeration, it is still worthwhile to create a `None` enumerated constant. The reason is that by default the memory used for the enumeration is initialized to zero by the common language runtime. Consequently, if you do not define a constant whose value is zero, the enumeration will contain an illegal value when it is created. - - If there is an obvious default case your application needs to represent, consider using an enumerated constant whose value is zero to represent the default. If there is no default case, consider using an enumerated constant whose value is zero that means the case that is not represented by any of the other enumerated constants. - -- Do not define an enumeration value solely to mirror the state of the enumeration itself. For example, do not define an enumerated constant that merely marks the end of the enumeration. If you need to determine the last value of the enumeration, check for that value explicitly. In addition, you can perform a range check for the first and last enumerated constant if all values within the range are valid. - -- Do not specify enumerated constants that are reserved for future use. - -- When you define a method or property that takes an enumerated constant as a value, consider validating the value. The reason is that you can cast a numeric value to the enumeration type even if that numeric value is not defined in the enumeration. - -## Examples - -The following example illustrates the use of the `FlagsAttribute` attribute and shows the effect on the method of using `FlagsAttribute` on an declaration. - -:::code language="csharp" source="./snippets/System/FlagsAttribute/Overview/csharp/flags.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/FlagsAttribute/Overview/fsharp/flags.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/FlagsAttribute/Overview/vb/flags.vb" id="Snippet1"::: - -The preceding example defines two color-related enumerations, `SingleHue` and `MultiHue`. The latter has the `FlagsAttribute` attribute; the former does not. The example shows the difference in behavior when a range of integers, including integers that do not represent underlying values of the enumeration type, are cast to the enumeration type and their string representations displayed. For example, note that 3 cannot be represented as a `SingleHue` value because 3 is not the underlying value of any `SingleHue` member, whereas the `FlagsAttribute` attribute makes it possible to represent 3 as a `MultiHue` value of `Black, Red`. - -The following example defines another enumeration with the `FlagsAttribute` attribute and shows how to use bitwise logical and equality operators to determine whether one or more bit fields are set in an enumeration value. You can also use the method to do that, but that is not shown in this example. - -:::code language="csharp" source="./snippets/System/FlagsAttribute/Overview/csharp/flags1.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/FlagsAttribute/Overview/fsharp/flags1.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/FlagsAttribute/Overview/vb/flags1.vb" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-gc.md b/docs/fundamentals/runtime-libraries/system-gc.md deleted file mode 100644 index e167d63afdf30..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-gc.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: System.GC class -description: Learn about the System.GC class. -ms.date: 12/31/2023 ---- -# System.GC class - -[!INCLUDE [context](includes/context.md)] - -The class controls the garbage collector. The garbage collector is a common language runtime component that controls the allocation and release of managed memory. The methods in this class influence when garbage collection is performed on an object and when resources allocated by an object are released. Properties in this class provide information about the total amount of memory available in the system and the age category, or generation, of memory allocated to an object. - -The garbage collector tracks and reclaims objects allocated in managed memory. Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. Alternatively, an application can force garbage collection using the method. - -Garbage collection consists of the following steps: - -1. The garbage collector searches for managed objects that are referenced in managed code. -2. The garbage collector tries to finalize objects that are not referenced. -3. The garbage collector frees objects that are not referenced and reclaims their memory. - -## Unmanaged resources - -During a collection, the garbage collector will not free an object if it finds one or more references to the object in managed code. However, the garbage collector does not recognize references to an object from unmanaged code, and might free objects that are being used exclusively in unmanaged code unless explicitly prevented from doing so. The method provides a mechanism that prevents the garbage collector from collecting objects that are still in use in unmanaged code. - -Aside from managed memory allocations, implementations of the garbage collector do not maintain information about resources held by an object, such as file handles or database connections. When a type uses unmanaged resources that must be released before instances of the type are reclaimed, the type can implement a finalizer. - -In most cases, finalizers are implemented by overriding the method; however, types written in C# or C++ implement destructors, which compilers turn into an override of . In most cases, if an object has a finalizer, the garbage collector calls it prior to freeing the object. However, the garbage collector is not required to call finalizers in all situations; for example, the method explicitly prevents an object's finalizer from being called. Also, the garbage collector is not required to use a specific thread to finalize objects, or guarantee the order in which finalizers are called for objects that reference each other but are otherwise available for garbage collection. - -In scenarios where resources must be released at a specific time, classes can implement the interface, which contains the method that performs resource management and cleanup tasks. Classes that implement must specify, as part of their class contract, if and when class consumers call the method to clean up the object. The garbage collector does not, by default, call the method; however, implementations of the method can call methods in the class to customize the finalization behavior of the garbage collector. - -For more information on object finalization and the dispose pattern, see [Cleaning Up Unmanaged Resources](../../standard/garbage-collection/unmanaged.md). - -## Object aging and generations - -The garbage collector in the common language runtime supports object aging using generations. A generation is a unit of measure of the relative age of objects in memory. The generation number, or age, of an object indicates the generation to which an object belongs. Objects created more recently are part of newer generations, and have lower generation numbers than objects created earlier in the application life cycle. Objects in the most recent generation are in generation 0. This implementation of the garbage collector supports three generations of objects, generations 0, 1, and 2. You can retrieve the value of the property to determine the maximum generation number supported by the system. - -Object aging allows applications to target garbage collection at a specific set of generations rather than requiring the garbage collector to evaluate all generations. Overloads of the method that include a `generation` parameter allow you to specify the oldest generation to be garbage collected. - -## Disallowing garbage collection - -The garbage collector supports a no GC region latency mode that can be used during the execution of critical paths in which garbage collection can adversely affect an app's performance. The no GC region latency mode requires that you specify an amount of memory that can be allocated without interference from the garbage collector. If the runtime can allocate that memory, the runtime will not perform a garbage collection while code in the critical path is executing. - -You define the beginning of the critical path of the no GC region by calling one of the overloads of the . You specify the end of its critical path by calling the method. - -You cannot nest calls to the method, and you should only call the method if the runtime is currently in no GC region latency mode. In other words, you should not call multiple times (after the first method call, subsequent calls will not succeed), and you should not expect calls to to succeed just because the first call to succeeded. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md deleted file mode 100644 index 0d7233dc9aa78..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-compareinfo.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: System.Globalization.CompareInfo class -description: Learn more about the System.Globalization.CompareInfo class. -ms.date: 12/28/2023 -ms.topic: concept-article ---- -# class - -[!INCLUDE [context](includes/context.md)] - -Conventions for comparing and sorting data vary from culture to culture. For example, sort order may be based on phonetics or on the visual representation of characters. In East Asian languages, characters are sorted by the stroke and radical of ideographs. Sorting also depends on the order languages and cultures use for the alphabet. For example, the Danish language has an "Æ" character that it sorts after "Z" in the alphabet. In addition, comparisons may be case-sensitive or case-insensitive, and casing rules may also differ by culture. The class is responsible for maintaining this culture-sensitive string comparison data and for performing culture-sensitive string operations. - -Typically, you do not have to instantiate a object directly, because one is used implicitly by all non-ordinal string comparison operations, including calls to the method. However, if you do want to retrieve a object, you can do it in one of these ways: - -- By retrieving the value of the property for a particular culture. - -- By calling the static method with a culture name. This allows for late-bound access to a object. - -## Ignored search values - -Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. Comparison methods such as and do not consider such characters when they perform a culture-sensitive comparison. Ignorable characters include: - -- . Culture-sensitive comparison methods will always find an empty string at the beginning (index zero) of the string being searched. - -- A character or string consisting of characters with code points that are not considered in the operation because of comparison options, In particular, the and options produce searches in which symbols and nonspacing combining characters are ignored. - -- A string with code points that have no linguistic significance. For example, a soft hyphen (U+00AD) is always ignored in a culture-sensitive string comparison. - -## Security considerations - -If a security decision depends on a string comparison or a case change, you should use the property to ensure that the behavior is consistent, regardless of the culture settings of the operating system. - -> [!NOTE] -> When possible, you should use string comparison methods that have a parameter of type to specify the kind of comparison expected. As a general rule, use linguistic options (using the current culture) for comparing strings displayed in the user interface and specify or for security comparisons. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-compareoptions.md b/docs/fundamentals/runtime-libraries/system-globalization-compareoptions.md deleted file mode 100644 index 48deba273484c..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-compareoptions.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: System.Globalization.CompareOptions enum -description: Learn more about the System.Globalization.CompareOptions enum. -ms.date: 12/28/2023 -ms.topic: concept-article ---- -# enum - -[!INCLUDE [context](includes/context.md)] - -The options denote case sensitivity or necessity to ignore types of characters. - -.NET uses three distinct ways of sorting: word sort, string sort, and ordinal sort. Word sort performs a culture-sensitive comparison of strings. Certain nonalphanumeric characters might have special weights assigned to them. For example, the hyphen ("-") might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. String sort is similar to word sort, except that there are no special cases. Therefore, all nonalphanumeric symbols come before all alphanumeric characters. Ordinal sort compares strings based on the Unicode values of each element of the string. For a downloadable set of text files that contain information on the character weights used in sorting and comparison operations for Windows operating systems, see [Sorting Weight Tables](https://www.microsoft.com/download/details.aspx?id=10921). For the sort weight table for Linux and macOS, see the [Default Unicode Collation Element Table](https://www.unicode.org/Public/UCA/latest/allkeys.txt). The specific version of the sort weight table on Linux and macOS depends on the version of the [International Components for Unicode](https://icu.unicode.org/) libraries installed on the system. For information on ICU versions and the Unicode versions that they implement, see [Downloading ICU](https://icu.unicode.org/download). - -The `StringSort` value can only be used with and . is thrown if the StringSort value is used with , , , or . - -> [!NOTE] -> When possible, you should use string comparison methods that accept a value to specify the kind of comparison expected. As a general rule, user-facing comparisons are best served by the use of linguistic options (using the current culture), while security comparisons should specify `Ordinal` or `OrdinalIgnoreCase`. - -## Culture-sensitive sorts - -[!INCLUDE[platform-note](includes/c-and-posix-cultures.md)] diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder-ctor.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder-ctor.md deleted file mode 100644 index 93ff83bca9bc9..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder-ctor.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: System.Globalization.CultureAndRegionInfoBuilder constructor -description: Learn about the System.Globalization.CultureAndRegionInfoBuilder constructor. -ms.date: 01/24/2024 ---- -# System.Globalization.CultureAndRegionInfoBuilder constructor - -[!INCLUDE [context](includes/context.md)] - -This article pertains to the constructor. - -The `cultureName` parameter specifies the name of the new object. - -The `flags` parameter is used for a value that specifies whether the new object is a new custom culture, or replaces an existing neutral culture, specific culture, or Windows locale. - -If the `cultureName` parameter specifies an existing .NET culture, registered custom culture, or culture generated from a Windows locale, the constructor automatically populates the new object with culture and country/region information. - -Populate the new object with culture and country/region information by invoking the and methods. - -## Custom culture names - -The preferred format of the `cultureName` parameter for a new, custom culture is "[`prefix`-]`language`[-`region`][-`suffix`[`…`]]", where the `language` component is required and the `prefix`, `region`, and `suffix` components are optional. The maximum length of each component is 8 characters and the maximum length of the entire `cultureName` parameter is 84 characters. - -The `prefix` component is the Internet Assigned Numbers Authority (IANA) identification. Specify "i-" or "I-" for culture names registered with the IANA, or "x-" or "X-" for culture names reserved for private use. Otherwise, the prefix is not required. For more information, see RFC 4646, "Tags for the Identification of Languages." - -The `language` component of the `cultureName` parameter specifies a lowercase two-letter code derived from ISO 639-1, and `region` specifies an uppercase two-letter code derived from ISO 3166. For example, en-US stands for English as spoken in the United States. The absence of the `region` component signifies a neutral culture. - -A `cultureName` that is the same as the name of a culture included with .NET signifies a replacement (override) culture. The values that can be assigned to the properties of a replacement culture are limited. For more information about such limitations, see the exceptions for each property. - -The application uses the `suffix` component to distinguish similar cultures. For example, two companies, ABC and XYZ, create and share a new ASP.NET Web service to promote their products in different markets around the world. The Web pages for the service display information such as the regional logo and local telephone number of each company depending on the user's culture. The culture-specific content for each Web page is in separate resource files identified by culture name and qualified by company name. For example, resource files for the en-US and ja-JP cultures are named en-US-ABC, en-US-XYZ, ja-JP-ABC, and ja-JP-XYZ. The "ABC" and "XYZ" suffixes enable the Web service to use the same application logic to display different market-specific information. - -The `suffix` component can consist of subcomponents, where each subcomponent is delimited by a hyphen and the maximum length of each subcomponent is 8 characters. For example, if "en-US-honda-cars" is the `cultureName` parameter, "-honda-cars" is the `suffix` component. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder.md deleted file mode 100644 index a2e037fe12081..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureandregioninfobuilder.md +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: System.Globalization.CultureAndRegionInfoBuilder class -description: Learn more about the System.Globalization.CultureAndRegionInfoBuilder class. -ms.date: 01/09/2024 -ms.topic: concept-article ---- -# class - -[!INCLUDE [context](includes/context.md)] - -> [!NOTE] -> The class is useful only for Windows operating systems. The generated *.nlp* files aren't supported on non-Windows operating systems. Also, even on Windows, the generated *.nlp* files are supported only on .NET Framework (or in .NET Core when using [NLS globalization mode](../../core/runtime-config/globalization.md#nls)). - -The class holds culture-specific information, such as the associated language, sublanguage, country/region, calendar, and cultural conventions. This class also provides culture-specific instances of the , , , and classes, which are required for culture-specific operations such as casing, formatting and parsing dates and numbers, and comparing strings. - -By default, .NET supports objects that represent a predefined set of cultures. For a list of these cultures available on Windows systems, see the **Language tag** column in the [list of language/region names supported by Windows](/openspecs/windows_protocols/ms-lcid/a9eac961-e77d-41a6-90a5-ce1a8b0cdb9c). Culture names follow the standard defined by [BCP 47](https://tools.ietf.org/html/bcp47). The class enables you to create a custom culture that is completely new or that overrides a predefined culture. When a custom culture is installed and registered on a particular computer, it becomes indistinguishable from predefined objects, and can be instantiated and used just like those objects. - -> [!IMPORTANT] -> The class is found in an assembly named *sysglobl.dll*. To successfully compile code that uses this type, you must add a reference to *sysglobl.dll*. - -A custom culture can be registered on a computer only by a user who has administrative rights on that computer. Consequently, apps typically do not create and install custom cultures. Instead, you can use the class to create a special-purpose tool that an administrator can use to create, install, and register a custom culture. After the custom culture is registered on a computer, you can use the class in your app to create instances of the custom culture just as you would for a predefined culture. - -If you parse date and time strings generated for a custom culture, you should use the or method instead of the or method to improve the probability that the parse operation will succeed. A date and time string for a custom culture can be complicated and therefore difficult to parse. The and methods try to parse a string with several implicit parse patterns, all of which might fail. The method, in contrast, requires the application to explicitly designate one or more exact parse patterns that are likely to succeed. - -## Define and create a custom culture - -You use the class to define and name a custom culture. The custom culture can be an entirely new culture, a new culture that is based on an existing culture (that is, a supplemental culture), or a culture that replaces an existing .NET culture. In each case, the basic steps are the same: - -1. Instantiate a object by calling its constructor. To replace an existing culture, pass that culture's name and the enumeration value to the constructor. To create a new culture or a supplemental culture, pass a unique culture name and either the or enumeration value. - - > [!NOTE] - > If you use the enumeration value to instantiate a object, the object's properties are automatically populated with values from the object to be replaced. - -2. If you're creating a new or supplemental culture: - - - Populate the object's properties by calling the method and passing a object whose property values are similar to your new object. - - Populate the object's regional properties by calling the method and passing a object that represents the region of your custom culture. - -3. Modify the properties of the object as necessary. - -4. If you are planning to register the custom culture in a separate routine, call the method. This generates an XML file that you can load and register in a separate custom culture installation routine. - -## Register a custom culture - -If you are developing a registration application for a custom culture that is separate from the application that creates the culture, you call the method to load the XML file that contains the custom culture's definition and instantiate the object. To handle the registration, call the method. For the registration to succeed, the application that registers the custom culture must be running with administrative privileges on the target system; otherwise, the call to throws an exception. - -> [!WARNING] -> Culture data can differ between systems. If you're using the class to create a custom culture that is uniform across multiple systems and you are creating your custom culture by loading data from existing and objects and customizing it, you should develop two different utilities. The first creates the custom culture and saves it to an XML file. The second uses the method to load the custom culture from an XML file and register it on the target computer. - -The registration process performs the following tasks: - -- Creates an *.nlp* file that contains the information that's defined in the object. -- Stores the *.nlp* file in the %windir%\Globalization system directory on the target computer. This enables the custom culture's settings to persist between sessions. (The method requires administrative privileges because the *.nlp* file is stored in a system directory.) -- Prepares .NET to search the %windir%\Globalization system directory instead of an internal cache the next time there's a request to create your new custom culture. - -When a custom culture is successfully registered, it's indistinguishable from the cultures that are predefined by .NET. The custom culture is available until a call to the method removes the *.nlp* file from the local computer. - -## Instantiate a custom culture - -You can create an instance of the custom culture in one of the following ways: - -- By invoking the constructor with the culture name. -- By calling the method with the culture name. -- By calling the method with the culture name. - -In addition, the array of objects that is returned by the method includes the custom culture. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentculture.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentculture.md deleted file mode 100644 index 16b09529cfd41..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentculture.md +++ /dev/null @@ -1,87 +0,0 @@ ---- -title: System.Globalization.CultureInfo.CurrentCulture property -description: Learn about the System.Globalization.CultureInfo.CurrentCulture property. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - VB ---- -# System.Globalization.CultureInfo.CurrentCulture property - -[!INCLUDE [context](includes/context.md)] - -The object that's returned by the property and its associated objects determines the default format for dates, times, numbers, and currency values, the sorting order of text, casing conventions, and string comparisons. - -The current culture is a property of the executing thread. When you set this property to a object that represents a new culture, the value of the `Thread.CurrentThread.CurrentCulture` property also changes. However, we recommend that you always use the property to retrieve and set the current culture. - -The `CultureInfo` object that this property returns is read-only. That means you can't mutate the existing object, for example, by changing the `DateTimeFormat`. To change the date-time format or some other aspect of the current culture, create a new `CultureInfo` object and assign it to the property. - -## How a thread's culture is determined - -When a thread is started, its culture is initially determined as follows: - -- By retrieving the culture that is specified by the property in the application domain in which the thread is executing, if the property value is not `null`. - -- If the thread is a thread pool thread that is executing a task-based asynchronous operation, its culture is determined by the culture of the calling thread. The following example changes the current culture to Portuguese (Brazil) and launches six tasks, each of which displays its thread ID, its task ID, and its current culture. Each of the tasks (and the threads) has inherited the culture of the calling thread. - - :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/Async1.cs" id="Snippet14"::: - :::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/vb/Async1.vb" id="Snippet14"::: - - For more information, see [Culture and task-based asynchronous operations](system-globalization-cultureinfo.md#culture-and-task-based-asynchronous-operations). - -- By calling the `GetUserDefaultLocaleName` function on Windows or the `uloc_getDefault` function from [ICU](https://icu-project.org/), which currently calls the POSIX `setlocale` function with category `LC_MESSAGES`, on Unix-like systems. - -Note that if you set a specific culture that is different from the system-installed culture or the user's preferred culture, and your application starts multiple threads, the current culture of those threads will be the culture that is returned by the `GetUserDefaultLocaleName` function, unless you assign a culture to the property in the application domain in which the thread is executing. - -For more information about how the culture of a thread is determined, see the "Culture and threads" section in the reference page. - -## Get the current culture - -The property is a per-thread setting; that is, each thread can have its own culture. You get the culture of the current thread by retrieving the value of the property, as the following example illustrates. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/Get1.cs" id="Snippet5"::: -:::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/vb/Get1.vb" id="Snippet5"::: - -## Set the CurrentCulture property explicitly - -To change the culture that's used by an existing thread, you set the property to the new culture. If you explicitly change a thread's culture in this way, that change persists if the thread crosses application domain boundaries. The following example changes the current thread culture to Dutch (Netherlands). It also shows that, when the current thread crosses application domain boundaries, its current culture remains changed. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/changeculture11.cs" id="Snippet11"::: -:::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/vb/changeculture11.vb" id="Snippet11"::: - -> [!NOTE] -> Changing the culture by using the property requires a permission with the value set. Manipulating threads is dangerous because of the security state associated with threads. Therefore, this permission should be given only to trustworthy code, and then only as necessary. You cannot change thread culture in semi-trusted code. - -Starting with .NET Framework 4, you can explicitly change the current thread culture to either a specific culture (such as French (Canada)) or a neutral culture (such as French). When a object represents a neutral culture, the values of properties such as , , , , and reflect the specific culture that is associated with the neutral culture. For example, the dominant culture for the English neutral culture is English (United States); the dominant culture for the German culture is German (Germany). The following example illustrates the difference in formatting when the current culture is set to a specific culture, French (Canada), and a neutral culture, French. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/specific12.cs" id="Snippet12"::: -:::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/vb/specific12.vb" id="Snippet12"::: - -You can also use the property along with the property to set the property of an ASP.NET application to the user's preferred culture, as the following example illustrates. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/csharp/aspculture13.cs" id="Snippet13"::: -:::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentCulture/vb/aspculture13.vb" id="Snippet13"::: - -## The current culture and user overrides - -Windows allows users to override the standard property values of the object and its associated objects by using **Regional and Language Options** in Control Panel. The object returned by the property reflects these user overrides in the following cases: - -- If the current thread culture is set implicitly by the Windows `GetUserDefaultLocaleName` function. - -- If the current thread culture defined by the property corresponds to the current Windows system culture. - -- If the current thread culture is set explicitly to a culture returned by the method, and that culture corresponds to the current Windows system culture. - -- If the current thread culture is set explicitly to a culture instantiated by the constructor, and that culture corresponds to the current Windows system culture. - -In some cases, particularly for server applications, setting the current culture to a object that reflects user overrides may be undesirable. Instead, you can set the current culture to a object that does not reflect user overrides in the following ways: - -- By calling the constructor with a value of `false` for the `useUserOverride` argument. - -- By calling the method, which returns a cached, read-only object. - -## The current culture and UWP apps - -In Universal Windows Platform (UWP) apps, the property is read-write, just as it is in .NET Framework and .NET Core apps; you can use it both to get and to set the current culture. However, UWP apps do not distinguish between the current culture and the current UI culture. The and properties map to the first value in the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection. - -In .NET Framework and .NET Core apps, the current culture is a per-thread setting, and the property reflects the culture of the current thread only. In UWP apps, the current culture maps to the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) property, which is a global setting. Setting the property changes the culture of the entire app; culture cannot be set on a per-thread basis. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentuiculture.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentuiculture.md deleted file mode 100644 index 65b9170b6de82..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-currentuiculture.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: System.Globalization.CultureInfo.CurrentUICulture property -description: Learn about the System.Globalization.CultureInfo.CurrentUICulture property. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - VB ---- -# System.Globalization.CultureInfo.CurrentUICulture property - -[!INCLUDE [context](includes/context.md)] - -The property is a per-thread property. That is, each thread has its own current UI culture. This property is equivalent to retrieving or setting the object assigned to the `System.Threading.Thread.CurrentThread.CurrentUICulture` property. When a thread is started, its UI culture is initially determined as follows: - -- By retrieving the culture that is specified by the property in the application domain in which the thread is executing, if the property value is not `null`. - -- If the thread is a thread pool thread that is executing a task-based asynchronous operation and the app targets the .NET Framework 4.6 or a later version of the .NET Framework, its UI culture is determined by the UI culture of the calling thread. The following example changes the current UI culture to Portuguese (Brazil) and launches six tasks, each of which displays its thread ID, its task ID, and its current UI culture. Each of the tasks (and the threads) has inherited the UI culture of the calling thread. - - :::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/Async1.cs" id="Snippet14"::: - :::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentUICulture/vb/Async1.vb" id="Snippet14"::: - - For more information, see the "Culture and task-based asynchronous operations" section in the documentation. - -- By calling the Windows `GetUserDefaultUILanguage` function. - -To change the user interface culture used by a thread, set the property to the new culture. If you explicitly change a thread's UI culture in this way, that change persists if the thread crosses application domain boundaries. - -> [!NOTE] -> If you set the property value to a object that represents a new culture, the value of the `Thread.CurrentThread.CurrentCulture` property also changes. - -## Get the current UI culture - -The property is a per-thread setting; that is, each thread can have its own UI culture. You get the UI culture of the current thread by retrieving the value of the property, as the following example illustrates. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/Get1.cs" id="Snippet5"::: -:::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentUICulture/vb/Get1.vb" id="Snippet5"::: - -You can also retrieve the value of the current thread's UI culture from the property. - -## Explicitly set the current UI culture - -Starting with .NET Framework 4.6, you can change the current UI culture by assigning a object that represents the new culture to the property. The current UI culture can be set to either a specific culture (such as en-US or de-DE) or to a neutral culture (such as en or de). The following example sets the current UI culture to fr-FR or French (France). - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/CurrentUICulture/csharp/currentuiculture1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Globalization/CultureInfo/CurrentUICulture/vb/currentuiculture1.vb" id="Snippet1"::: - -In a multithreaded application, you can explicitly set the UI culture of any thread by assigning a object that represents that culture to the thread's property. If the thread whose culture you want to set is the current thread, you can assign the new culture to the property. When the UI culture of a thread is set explicitly, that thread retains the same culture even if it crosses application domain boundaries and executes code in another application domain. - -## Implicitly set the current UI culture - -When a thread, including the main application thread, is first created, by default its current UI culture is set as follows: - -- By using the culture defined by the property for the current application domain if the property value is not `null`. -- By using the system's default culture. On systems that use the Windows operating system, the common language runtime calls the Windows `GetUserDefaultUILanguage` function to set the current UI culture. `GetUserDefaultUILanguage` returns the default UI culture set by the user. If the user has not set a default UI language, it returns the culture originally installed on the system. - -If the thread crosses application boundaries and executes code in another application domain, its culture is determined in the same way as that of a newly created thread. - -Note that if you set a specific UI culture that is different from the system-installed UI culture or the user's preferred UI culture, and your application starts multiple threads, the current UI culture of those threads will be the culture returned by the `GetUserDefaultUILanguage` function, unless you assign a culture to the property in the application domain in which the thread is executing. - -## Security considerations - -Changing the culture of the current thread requires a permission with the value set. - -> [!CAUTION] -> Manipulating threads is dangerous because of the security state associated with threads. Therefore, this permission should be given only to trustworthy code, and then only as necessary. You cannot change thread culture in semi-trusted code. - -## The current UI culture and UWP apps - -In Universal Windows Platform (UWP) apps, the property is read-write, just as it is in .NET Framework and .NET Core apps; you can use it both to get and to set the current culture. However, UWP apps do not distinguish between the current culture and the current UI culture. The and properties map to the first value in the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection. - -In .NET Framework and .NET Core apps, the current UI culture is a per-thread setting, and the property reflects the UI culture of the current thread only. In UWP apps, the current culture maps to the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) property, which is a global setting. Setting the property changes the culture of the entire app; culture cannot be set on a per-thread basis. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-invariantculture.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-invariantculture.md deleted file mode 100644 index ea55c997a112d..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo-invariantculture.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: System.Globalization.CultureInfo.InvariantCulture property -description: Learn about the System.Globalization.CultureInfo.InvariantCulture property. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - VB ---- -# System.Globalization.CultureInfo.InvariantCulture property - -[!INCLUDE [context](includes/context.md)] - -The invariant culture is culture-insensitive; it's associated with the English language but not with any country/region. You specify the invariant culture by name by using an empty string ("") in the call to a instantiation method. This property, , also retrieves an instance of the invariant culture. It can be used in almost any method in the namespace that requires a culture. The objects returned by properties such as , , and also reflect the string comparison and formatting conventions of the invariant culture. - -Unlike culture-sensitive data, which is subject to change by user customization or by updates to the .NET Framework or the operating system, invariant culture data is stable over time and across installed cultures and cannot be customized by users. This makes the invariant culture particularly useful for operations that require culture-independent results, such as formatting and parsing operations that persist formatted data, or sorting and ordering operations that require that data be displayed in a fixed order regardless of culture. - -## String operations - -You can use the invariant culture for culture-sensitive string operations that are not affected by the conventions of the current culture and that are consistent across cultures. For example, you may want sorted data to appear in a fixed order or apply a standard set of casing conventions to strings regardless of the current culture. To do this, you pass the object to a method that has a parameter, such as and . - -## Persisting data - -The property can be used to persist data in a culture-independent format. This provides a known format that does not change and that can be used to serialize and deserialize data across cultures. After the data is deserialized, it can be formatted appropriately based on the cultural conventions of the current user. - -For example, if you choose to persist date and time data in string form, you can pass the object to the or method to create the string, and you can pass the object to the or method to convert the string back to a date and time value. This technique ensures that the underlying date and time values do not change when the data is read or written by users from different cultures. - -The following example uses the invariant culture to persist a value as a string. It then parses the string and displays its value by using the formatting conventions of the French (France) and German (Germany) cultures. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/InvariantCulture/csharp/persist1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Globalization/CultureInfo/InvariantCulture/vb/persist1.vb" id="Snippet1"::: - -## Security decisions - -If you are making a security decision (such as whether to allow access to a system resource) based on the result of a string comparison or a case change, you should not use the invariant culture. Instead, you should perform a case-sensitive or case-insensitive ordinal comparison by calling a method that includes a parameter and supplying either or as an argument. Code that performs culture-sensitive string operations can cause security vulnerabilities if the current culture is changed or if the culture on the computer that is running the code differs from the culture that is used to test the code. In contrast, an ordinal comparison depends solely on the binary value of the compared characters. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md deleted file mode 100644 index b79eccc24ce38..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-cultureinfo.md +++ /dev/null @@ -1,227 +0,0 @@ ---- -title: System.Globalization.CultureInfo class -description: Learn more about the System.Globalization.CultureInfo class. -ms.date: 12/28/2023 -ms.topic: concept-article ---- -# class - -[!INCLUDE [context](includes/context.md)] - -The class provides culture-specific information, such as the language, sublanguage, country/region, calendar, and conventions associated with a particular culture. This class also provides access to culture-specific instances of the , , , and objects. These objects contain the information required for culture-specific operations, such as casing, formatting dates and numbers, and comparing strings. The class is used either directly or indirectly by classes that format, parse, or manipulate culture-specific data, such as , , , and the numeric types. - -## Culture names and identifiers - -The class specifies a unique name for each culture, based on RFC 4646. The name is a combination of an ISO 639 two-letter or three-letter lowercase culture code associated with a language and an ISO 3166 two-letter uppercase subculture code associated with a country or region. In addition, for apps that are running under Windows 10 or later, culture names that correspond to valid BCP-47 language tags are supported. - -> [!NOTE] -> When a culture name is passed to a class constructor or a method such as or , its case is not significant. - -The format for the culture name based on RFC 4646 is *`languagecode2`*-*`country/regioncode2`*, where *`languagecode2`* is the two-letter language code and *`country/regioncode2`* is the two-letter subculture code. Examples include `ja-JP` for Japanese (Japan) and `en-US` for English (United States). In cases where a two-letter language code is not available, a three-letter code as defined in ISO 639-3 is used. - -Some culture names also specify an ISO 15924 script. For example, Cyrl specifies the Cyrillic script and Latn specifies the Latin script. A culture name that includes a script uses the pattern *`languagecode2`*-*`scripttag`*-*`country/regioncode2`*. An example of this type of culture name is `uz-Cyrl-UZ` for Uzbek (Cyrillic, Uzbekistan). On Windows operating systems before Windows Vista, a culture name that includes a script uses the pattern *`languagecode2`*-*`country/regioncode2`*-*`scripttag`*, for example, `uz-UZ-Cyrl` for Uzbek (Cyrillic, Uzbekistan). - -A neutral culture is specified by only the two-letter, lowercase language code. For example, `fr` specifies the neutral culture for French, and `de` specifies the neutral culture for German. - -> [!NOTE] -> There are two culture names that contradict this rule. The cultures Chinese (Simplified), named `zh-Hans`, and Chinese (Traditional), named `zh-Hant`, are neutral cultures. The culture names represent the current standard and should be used unless you have a reason for using the older names `zh-CHS` and `zh-CHT`. - -A culture identifier is a standard international numeric abbreviation and has the components necessary to uniquely identify one of the installed cultures. Your application can use predefined culture identifiers or define custom identifiers. - -Certain predefined culture names and identifiers are used by this and other classes in the namespace. For detailed culture information for Windows systems, see the **Language tag** column in the [list of language/region names supported by Windows](/openspecs/windows_protocols/ms-lcid/a9eac961-e77d-41a6-90a5-ce1a8b0cdb9c). Culture names follow the standard defined by [BCP 47](https://tools.ietf.org/html/bcp47). - -The culture names and identifiers represent only a subset of cultures that can be found on a particular computer. Windows versions or service packs can change the available cultures. Applications can add custom cultures using the class. Users can add their own custom cultures using the [Microsoft Locale Builder](https://www.microsoft.com/download/details.aspx?id=41158) tool. Microsoft Locale Builder is written in managed code using the `CultureAndRegionInfoBuilder` class. - -Several distinct names are closely associated with a culture, notably the names associated with the following class members: - -- -- -- - -## Invariant, neutral, and specific cultures - -The cultures are generally grouped into three sets: invariant cultures, neutral cultures, and specific cultures. - -An invariant culture is culture-insensitive. Your application specifies the invariant culture by name using an empty string ("") or by its identifier. defines an instance of the invariant culture. It is associated with the English language but not with any country/region. It is used in almost any method in the `Globalization` namespace that requires a culture. - -A neutral culture is a culture that is associated with a language but not with a country/region. A specific culture is a culture that is associated with a language and a country/region. For example, `fr` is the neutral name for the French culture, and `fr-FR` is the name of the specific French (France) culture. Note that Chinese (Simplified) and Chinese (Traditional) are also considered neutral cultures. - -Creating an instance of a class for a neutral culture is not recommended because the data it contains is arbitrary. To display and sort data, specify both the language and region. Additionally, the property of a object created for a neutral culture returns only the country and does not include the region. - -The defined cultures have a hierarchy in which the parent of a specific culture is a neutral culture and the parent of a neutral culture is the invariant culture. The property contains the neutral culture associated with a specific culture. Custom cultures should define the property in conformance with this pattern. - -If the resources for a specific culture are not available in the operating system, the resources for the associated neutral culture are used. If the resources for the neutral culture are not available, the resources embedded in the main assembly are used. For more information on the resource fallback process, see [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps). - -The list of locales in the Windows API is slightly different from the list of cultures supported by .NET. If interoperability with Windows is required, for example, through the p/invoke mechanism, the application should use a specific culture that's defined for the operating system. Use of the specific culture ensures consistency with the equivalent Windows locale, which is identified with a locale identifier that is the same as . - -A or a can be created only for the invariant culture or for specific cultures, not for neutral cultures. - -If is the but the is not set to `zh-TW`, then , , and return an empty string (""). - -## Custom cultures - -On Windows, you can create custom locales. For more information, see [Custom locales](/windows/win32/intl/custom-locales). - -## CultureInfo and cultural data - -.NET derives its cultural data from a one of a variety of sources, depending on implementation, platform, and version: - -- In all versions of .NET (Core) running on Unix platforms or Windows 10 and later versions, cultural data is provided by the [International Components for Unicode (ICU) Library](https://icu.unicode.org/). The specific version of the ICU Library depends on the individual operating system. -- In all versions of .NET (Core) running on Windows 9 and earlier versions, cultural data is provided by the Windows operating system. -- In .NET Framework 4 and later versions, cultural data is provided by the Windows operating system. - -Because of this, a culture available on a particular .NET implementation, platform, or version may not be available on a different .NET implementation, platform, or version. - -Some `CultureInfo` objects differ depending on the underlying platform. In particular, `zh-CN`, or Chinese (Simplified, China) and `zh-TW`, or Chinese (Traditional, Taiwan), are available cultures on Windows systems, but they are aliased cultures on Unix systems. "zh-CN" is an alias for the "zh-Hans-CN" culture, and "zh-TW" is an alias for the "zh-Hant-TW" culture. Aliased cultures are not returned by calls to the method and may have different property values, including different cultures, than their Windows counterparts. For the `zh-CN` and `zh-TW` cultures, these differences include the following: - -- On Windows systems, the parent culture of the "zh-CN" culture is "zh-Hans", and the parent culture of the "zh-TW" culture is "zh-Hant". The parent culture of both these cultures is "zh". On Unix systems, the parents of both cultures are "zh". This means that, if you don't provide culture-specific resources for the "zh-CN" or "zh-TW" cultures but do provide a resources for the neutral "zh-Hans" or "zh-Hant" culture, your application will load the resources for the neutral culture on Windows but not on Unix. On Unix systems, you must explicitly set the thread's to either "zh-Hans" or "zh-Hant". - -- On Windows systems, calling on an instance that represents the "zh-CN" culture and passing it a "zh-Hans-CN" instance returns `true`. On Unix systems, the method call returns `false`. This behavior also applies to calling on a "zh-TW" instance and passing it a "zh-Hant-Tw" instance. - -## Dynamic culture data - -Except for the invariant culture, culture data is dynamic. This is true even for the predefined cultures. For example, countries or regions adopt new currencies, change their spellings of words, or change their preferred calendar, and culture definitions change to track this. Custom cultures are subject to change without notice, and any specific culture might be overridden by a custom replacement culture. Also, as discussed below, an individual user can override cultural preferences. Applications should always obtain culture data at runtime. - -> [!CAUTION] -> When saving data, your application should use the invariant culture, a binary format, or a specific culture-independent format. Data saved according to the current values associated with a particular culture, other than the invariant culture, might become unreadable or might change in meaning if that culture changes. - -## The current culture and current UI culture - -Every thread in a .NET application has a current culture and a current UI culture. The current culture determines the formatting conventions for dates, times, numbers, and currency values, the sort order of text, casing conventions, and the ways in which strings are compared. The current UI culture is used to retrieve culture-specific resources at runtime. - -> [!NOTE] -> For information on how the current and current UI culture is determined on a per-thread basis, see the [Culture and threads](#culture-and-threads) section. For information on how the current and current UI culture is determined on threads executing in a new application domain, and on threads that cross application domain boundaries, see the [Culture and application domains](#culture-and-application-domains) section. For information on how the current and current UI culture is determined on threads performing task-based asynchronous operations, see the [Culture and task-based asynchronous operations](#culture-and-task-based-asynchronous-operations) section. - -For more detailed information on the current culture, see the property. For more detailed information on the current UI culture, see the property topic. - -### Retrieve the current and current UI cultures - -You can get a object that represents the current culture in either of two ways: - -- By retrieving the value of the property. -- By retrieving the value of the [Thread.CurrentThread.CurrentCulture]() property. - -The following example retrieves both property values, compares them to show that they are equal, and displays the name of the current culture. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/Current1.cs" id="Snippet1"::: - -You can get a object that represents the current UI culture in either of two ways: - -- By retrieving the value of the property. - -- By retrieving the value of the [Thread.CurrentThread.CurrentUICulture]() property. - -The following example retrieves both property values, compares them to show that they are equal, and displays the name of the current UI culture. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/CurrentUI1.cs" id="Snippet2"::: - -### Set the current and current UI cultures - -To change the culture and UI culture of a thread, do the following: - -1. Instantiate a object that represents that culture by calling a class constructor and passing it the name of the culture. The constructor instantiates a object that reflects user overrides if the new culture is the same as the current Windows culture. The constructor allows you to specify whether the newly instantiated object reflects user overrides if the new culture is the same as the current Windows culture. - -2. Assign the object to the or property on .NET Core and .NET Framework 4.6 and later versions. - -The following example retrieves the current culture. If it is anything other than the French (France) culture, it changes the current culture to French (France). Otherwise, it changes the current culture to French (Luxembourg). - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/Change1.cs" id="Snippet3"::: - -The following example retrieves the current culture. If it is anything other the Slovenian (Slovenia) culture, it changes the current culture to Slovenian (Slovenia). Otherwise, it changes the current culture to Croatian (Croatia). - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/ChangeUI1.cs" id="Snippet4"::: - -## Get all cultures - -You can retrieve an array of specific categories of cultures or of all the cultures available on the local computer by calling the method. For example, you can retrieve custom cultures, specific cultures, or neutral cultures either alone or in combination. - -The following example calls the method twice, first with the enumeration member to retrieve all custom cultures, and then with the enumeration member to retrieve all replacement cultures. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/GetCultures1.cs" id="Snippet5"::: - -## Culture and threads - -When a new application thread is started, its current culture and current UI culture are defined by the current system culture, and not by the current thread culture. The following example illustrates the difference. It sets the current culture and current UI culture of an application thread to the French (France) culture (fr-FR). If the current culture is already fr-FR, the example sets it to the English (United States) culture (en-US). It displays three random numbers as currency values and then creates a new thread, which, in turn, displays three more random numbers as currency values. But as the output from the example shows, the currency values displayed by the new thread do not reflect the formatting conventions of the French (France) culture, unlike the output from the main application thread. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/defaultthread1.cs" id="Snippet1"::: - -You can set the culture and UI culture of all threads in an application domain by assigning a object that represents that culture to the and properties. The following example uses these properties to ensure that all threads in the default application domain share the same culture. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/setthreads1.cs" id="Snippet3"::: - -> [!WARNING] -> Although the and properties are static members, they define the default culture and default UI culture only for the application domain that is current at the time these property values are set. For more information, see the next section, [Culture and application domains](#culture-and-application-domains). - -When you assign values to the and properties, the culture and UI culture of the threads in the application domain also change if they have not explicitly been assigned a culture. However, these threads reflect the new culture settings only while they execute in the current application domain. If these threads execute in another application domain, their culture becomes the default culture defined for that application domain. As a result, we recommend that you always set the culture of the main application thread, and not rely on the and properties to change it. - -## Culture and application domains - - and are static properties that explicitly define a default culture only for the application domain that is current when the property value is set or retrieved. The following example sets the default culture and default UI culture in the default application domain to French (France), and then uses the class and the delegate to set the default culture and UI culture in a new application domain to Russian (Russia). A single thread then executes two methods in each application domain. Note that the thread's culture and UI culture are not explicitly set; they are derived from the default culture and UI culture of the application domain in which the thread is executing. Note also that the and properties return the default values of the application domain that is current when the method call is made. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/appdomainex1.cs" id="Snippet1"::: - -For more information about cultures and application domains, see the "Application Domains and Threads" section in the [Application Domains](../../framework/app-domains/application-domains.md) topic. - -## Culture and task-based asynchronous operations - -The [task-based asynchronous programming pattern](../../standard/parallel-programming/task-based-asynchronous-programming.md) uses and objects to asynchronously execute delegates on thread pool threads. The specific thread on which a particular task runs is not known in advance, but is determined only at runtime. - -For apps that target .NET Framework 4.6 or a later version, culture is part of an asynchronous operation's context. In other words, asynchronous operations by default inherit the values of the and properties of the thread from which they are launched. If the current culture or current UI culture differs from the system culture, the current culture crosses thread boundaries and becomes the current culture of the thread pool thread that is executing an asynchronous operation. - -The following example provides a simple illustration. The example defines a delegate, `formatDelegate`, that returns some numbers formatted as currency values. The example changes the current system culture to either French (France) or, if French (France) is already the current culture, English (United States). It then: - -- Invokes the delegate directly so that it runs synchronously on the main app thread. -- Creates a task that executes the delegate asynchronously on a thread pool thread. -- Creates a task that executes the delegate synchronously on the main app thread by calling the method. - -As the output from the example shows, when the current culture is changed to French (France), the current culture of the thread from which tasks are invoked asynchronously becomes the current culture for that asynchronous operation. - -:::code language="csharp" source="./snippets/System.Globalization/CultureInfo/csharp/asyncculture1.cs" id="Snippet1"::: - - and are per-app domain properties; that is, they establish a default culture for all threads not explicitly assigned a culture in a specific application domain. However, for apps that target .NET Framework 4.6 or later, the culture of the calling thread remains part of an asynchronous task's context even if the task crosses app domain boundaries. - -## CultureInfo object serialization - -When a object is serialized, all that is actually stored is and . It is successfully deserialized only in an environment where that has the same meaning. The following three examples show why this is not always the case: - -- If the property value is , and if that culture was first introduced in a particular version of the Windows operating system, it is not possible to deserialize it on an earlier version of Windows. For example, if a culture was introduced in Windows 10, it cannot be deserialized on Windows 8. - -- If the value is , and the computer on which it is deserialized does not have this user custom culture installed, it is not possible to deserialize it. - -- If the value is , and the computer on which it is deserialized does not have this replacement culture, it deserializes to the same name, but not all of the same characteristics. For example, if `en-US` is a replacement culture on computer A, but not on computer B, and if a object referring to this culture is serialized on computer A and deserialized on computer B, then none of the custom characteristics of the culture are transmitted. The culture deserializes successfully, but with a different meaning. - -## Control Panel overrides - -The user might choose to override some of the values associated with the current culture of Windows through the regional and language options portion of Control Panel. For example, the user might choose to display the date in a different format or to use a currency other than the default for the culture. In general, your applications should honor these user overrides. - -If is `true` and the specified culture matches the current culture of Windows, the uses those overrides, including user settings for the properties of the instance returned by the property, and the properties of the instance returned by the property. If the user settings are incompatible with the culture associated with the , for example, if the selected calendar is not one of the , the results of the methods and the values of the properties are undefined. - -## Alternate sort orders - -Some cultures support more than one sort order. For example: - -- The Spanish (Spain) culture has two sort orders: the default international sort order, and the traditional sort order. When you instantiate a object with the `es-ES` culture name, the international sort order is used. When you instantiate a object with the `es-ES-tradnl` culture name, the traditional sort order is used. - -- The `zh-CN` (Chinese (Simplified, PRC)) culture supports two sort orders: by pronunciation (the default) and by stroke count. When you instantiate a object with the `zh-CN` culture name, the default sort order is used. When you instantiate a object with a local identifier of 0x00020804, strings are sorted by stroke count. - -The following table lists the cultures that support alternate sort orders and the identifiers for the default and alternate sort orders. - -|Culture name|Culture|Default sort name and identifier|Alternate sort name and identifier| -|------------------|-------------|--------------------------------------|----------------------------------------| -|es-ES|Spanish (Spain)|International: 0x00000C0A|Traditional: 0x0000040A| -|zh-TW|Chinese (Taiwan)|Stroke Count: 0x00000404|Bopomofo: 0x00030404| -|zh-CN|Chinese (PRC)|Pronunciation: 0x00000804|Stroke Count: 0x00020804| -|zh-HK|Chinese (Hong Kong SAR)|Stroke Count: 0x00000c04|Stroke Count: 0x00020c04| -|zh-SG|Chinese (Singapore)|Pronunciation: 0x00001004|Stroke Count: 0x00021004| -|zh-MO|Chinese (Macao SAR)|Pronunciation: 0x00001404|Stroke Count: 0x00021404| -|ja-JP|Japanese (Japan)|Default: 0x00000411|Unicode: 0x00010411| -|ko-KR|Korean (Korea)|Default: 0x00000412|Korean Xwansung - Unicode: 0x00010412| -|de-DE|German (Germany)|Dictionary: 0x00000407|Phone Book Sort DIN: 0x00010407| -|hu-HU|Hungarian (Hungary)|Default: 0x0000040e|Technical Sort: 0x0001040e| -|ka-GE|Georgian (Georgia)|Traditional: 0x00000437|Modern Sort: 0x00010437| - -## The current culture and UWP apps - -In Universal Windows Platform (UWP) apps, the and properties are read-write, just as they are in .NET Framework and .NET Core apps. However, UWP apps recognize a single culture. The and properties map to the first value in the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection. - -In .NET apps, the current culture is a per-thread setting, and the and properties reflect the culture and UI culture of the current thread only. In UWP apps, the current culture maps to the [Windows.ApplicationModel.Resources.Core.ResourceManager.DefaultContext.Languages](/uwp/api/windows.applicationmodel.resources.core.resourcecontext#properties_) collection, which is a global setting. Setting the or property changes the culture of the entire app; culture cannot be set on a per-thread basis. diff --git a/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md deleted file mode 100644 index 9d5976795dbf0..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-datetimeformatinfo.md +++ /dev/null @@ -1,282 +0,0 @@ ---- -title: System.Globalization.DateTimeFormatInfo class -description: Learn more about the System.Globalization.DateTimeFormatInfo class. -ms.date: 12/28/2023 -ms.topic: concept-article ---- -# class - -[!INCLUDE [context](includes/context.md)] - -The properties of the class contain culture-specific information for formatting or parsing date and time values such as the following: - -- The patterns used to format date values. -- The patterns used to format time values. -- The names of the days of the week. -- The names of the months of the year. -- The A.M. and P.M. designators used in time values. -- The calendar in which dates are expressed. - -## Instantiate a DateTimeFormatInfo object - -A object can represent the formatting conventions of the invariant culture, a specific culture, a neutral culture, or the current culture. This section discusses how to instantiate each type of object. - -### Instantiate a DateTimeFormatInfo object for the invariant culture - -The invariant culture represents a culture that is culture-insensitive. It is based on the English language, but not on any specific English-speaking country/region. Although the data of specific cultures can be dynamic and can change to reflect new cultural conventions or user preferences, the data of the invariant culture does not change. You can instantiate a object that represents the formatting conventions of the invariant culture in the following ways: - -- By retrieving the value of the property. The returned object is read-only. -- By calling the parameterless constructor. The returned object is read/write. -- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. - -The following example uses each of these methods to instantiate a object that represents the invariant culture. It then indicates whether the object is read-only. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/create1.cs" id="Snippet1"::: - -### Instantiate a DateTimeFormatInfo object for a specific culture - -A specific culture represents a language that is spoken in a particular country/region. For example, en-US is a specific culture that represents the English language spoken in the United States, and en-CA is a specific culture that represents the English language spoken in Canada. You can instantiate a object that represents the formatting conventions of a specific culture in the following ways: - -- By calling the method and retrieving the value of the returned object's property. The returned object is read-only. - -- By passing the static method a object that represents the culture whose object you want to retrieve. The returned object is read/write. - -- By calling the static method and retrieving the value of the returned object's property. The returned object is read/write. - -- By calling the class constructor and retrieving the value of the returned object's property. The returned object is read/write. - -The following example illustrates each of these ways to instantiate a object and indicates whether the resulting object is read-only. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/create1.cs" id="Snippet3"::: - -### Instantiate a DateTimeFormatInfo object for a neutral culture - -A neutral culture represents a culture or language that is independent of a country/region; it is typically the parent of one or more specific cultures. For example, Fr is a neutral culture for the French language and the parent of the fr-FR culture. You can instantiate a object that represents the formatting conventions of a neutral culture in the same ways that you create a object that represents the formatting conventions of a specific culture. In addition, you can retrieve a neutral culture's object by retrieving a neutral culture from a specific culture's property and retrieving the object returned by its property. Unless the parent culture represents the invariant culture, the returned object is read/write. The following example illustrates these ways of instantiating a object that represents a neutral culture. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/create1.cs" id="Snippet2"::: - -However, a neutral culture lacks culture-specific formatting information, because it is independent of a specific country/region. Instead of populating the object with generic values, .NET returns a object that reflects the formatting conventions of a specific culture that is a child of the neutral culture. For example, the object for the neutral en culture reflects the formatting conventions of the en-US culture, and the object for the fr culture reflects the formatting conventions of the fr-FR culture. - -You can use code like the following to determine which specific culture's formatting conventions a neutral culture represents. The example uses reflection to compare the properties of a neutral culture with the properties of a specific child culture. It considers two calendars to be equivalent if they are the same calendar type and, for Gregorian calendars, if their properties have identical values. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate6.cs" id="Snippet6"::: - -### Instantiate a DateTimeFormatInfo object for the current culture - -You can instantiate a object that represents the formatting conventions of the current culture in the following ways: - -- By retrieving the value of the property. The returned object is read-only. - -- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. - -- By calling the method with a object that represents the current culture. The returned object is read-only. - -The following example uses each of these methods to instantiate a object that represents the formatting conventions of the current culture. It then indicates whether the object is read-only. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/create2.cs" id="Snippet4"::: - -You can create a writable object that represents the conventions of the current culture in one of these ways: - -- By retrieving a object in any of the three previous ways and calling the method on the returned object. This creates a copy of the original object, except that its property is `false`. - -- By calling the method to create a object that represents the current culture, and then using its property to retrieve the object. - -The following example illustrates each way of instantiating a read/write object and displays the value of its property. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate2.cs" id="Snippet7"::: - -In Windows, the user can override some of the property values used in formatting and parsing operations through the **Region and Language** application in Control Panel. For example, a user whose culture is English (United States) might choose to display long time values using a 24-hour clock (in the format HH:mm:ss) instead of the default 12-hour clock (in the format h:mm:ss tt). The objects retrieved in the ways discussed previously all reflect these user overrides. If this is undesirable, you can create a object that does not reflect user overrides (and is also read/write instead of read-only) by calling the constructor and supplying a value of `false` for the `useUserOverride` argument. The following example illustrates this for a system whose current culture is English (United States) and whose long time pattern has been changed from the default of h:mm:ss tt to HH:mm:ss. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/instantiate3.cs" id="Snippet8"::: - -## DateTimeFormatInfo and dynamic data - -The culture-specific data for formatting date and time values provided by the class is dynamic, just like cultural data provided by the class. You should not make any assumptions about the stability of values for objects that are associated with particular objects. Only the data provided by the invariant culture and its associated object is stable. Other data can change between application sessions or even while your application is running. There are four major sources of change: - -- System updates. Cultural preferences such as the preferred calendar or customary date and time formats change over time. When this happens, Windows Update includes changes to the property value for a particular culture. - -- Replacement cultures. The class can be used to replace the data of an existing culture. - -- Cascading changes to property values. A number of culture-related properties can change at runtime, which, in turn, causes data to change. For example, the current culture can be changed either programmatically or through user action. When this happens, the object returned by the property changes to an object associated with the current culture. Similarly, a culture's calendar can change, which can result in changes to numerous property values. - -- User preferences. Users of your application might choose to override some of the values associated with the current system culture through the regional and language options in Control Panel. For example, users might choose to display the date in a different format. If the property is set to `true`, the properties of the object is also retrieved from the user settings. If the user settings are incompatible with the culture associated with the object (for example, if the selected calendar is not one of the calendars indicated by the property), the results of the methods and the values of the properties are undefined. - -To minimize the possibility of inconsistent data, all user-overridable properties of a object are initialized when the object is created. There is still a possibility of inconsistency, because neither object creation nor the user override process is atomic and the relevant values can change during object creation. However, this situation should be extremely rare. - -You can control whether user overrides are reflected in objects that represent the same culture as the system culture. The following table lists the ways in which a object can be retrieved and indicates whether the resulting object reflects user overrides. - -|Source of CultureInfo and DateTimeFormatInfo object|Reflects user overrides| -|---------------------------------------------------------|-----------------------------| -|`CultureInfo.CurrentCulture.DateTimeFormat` property|Yes| -| property|Yes| -| method|Yes| -| method|No| -| constructor|Yes| -| constructor|Depends on value of `useUserOverride` parameter| - -Unless there is a compelling reason to do otherwise, you should respect user overrides when you use the object in client applications to format and parse user input or to display data. For server applications or unattended applications, you should not. However, if you are using the object either explicitly or implicitly to persist date and time data in string form, you should either use a object that reflects the formatting conventions of the invariant culture, or you should specify a custom date and time format string that you use regardless of culture. - -## Format dates and times - -A object is used implicitly or explicitly in all date and time formatting operations. These include calls to the following methods: - -- All date and time formatting methods, such as and . -- The major composite formatting method, which is . -- Other composite formatting methods, such as and . - -All date and time formatting operations make use of an implementation. The interface includes a single method, . This callback method is passed a object that represents the type needed to provide formatting information. The method returns either an instance of that type or `null` if it cannot provide an instance of the type. .NET includes two implementations for formatting dates and times: - -- The class, which represents a specific culture (or a specific language in a specific country/region). In a date and time formatting operation, the method returns the object associated with its property. -- The class, which provides information about the formatting conventions of its associated culture. The method returns an instance of itself. - -If an implementation is not provided to a formatting method explicitly, the object returned by the property that represents the current culture is used. - -The following example illustrates the relationship between the interface and the class in formatting operations. It defines a custom implementation whose method displays the type of the object requested by the formatting operation. If it is requesting a object, the method provides the object for the current culture. As the output from the example shows, the method requests a object to provide formatting information, whereas the method requests and objects as well as an implementation. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/formatprovider1.cs" id="Snippet9"::: - -## Format strings and DateTimeFormatInfo properties - -The object includes three kinds of properties that are used in formatting operations with date and time values: - -- Calendar-related properties. Properties such as , , , and , are associated with the calendar used by the culture, which is defined by the property. These properties are used for long date and time formats. - -- Properties that produce a standards-defined result string. The , , and properties contain custom format strings that produce result strings defined by international standards. These properties are read-only and cannot be modified. - -- Properties that define culture-sensitive result strings. Some properties, such as and , contain [custom format strings](../../standard/base-types/custom-date-and-time-format-strings.md) that specify the format of the result string. Others, such as , , , and , define culture-sensitive symbols or substrings that can be included in a result string. - -The [standard date and time format strings](../../standard/base-types/standard-date-and-time-format-strings.md), such as "d", "D", "f", and "F", are aliases that correspond to particular format pattern properties. Most of the [custom date and time format strings](../../standard/base-types/custom-date-and-time-format-strings.md) are related to strings or substrings that a formatting operation inserts into the result stream. The following table lists the standard and custom date and time format specifiers and their associated properties. For details about how to use these format specifiers, see [Standard Date and Time Format Strings](../../standard/base-types/standard-date-and-time-format-strings.md) and [Custom Date and Time Format Strings](../../standard/base-types/custom-date-and-time-format-strings.md). Note that each standard format string corresponds to a property whose value is a custom date and time format string. The individual specifiers in this custom format string in turn correspond to other properties. The table lists only the properties for which the standard format strings are aliases, and does not list properties that may be accessed by custom format strings assigned to those aliased properties. In addition, the table lists only custom format specifiers that correspond to properties. - -|Format specifier|Associated properties| -|----------------------|---------------------------| -|"d" (short date; standard format string)|, to define the overall format of the result string.| -|"D" (long date; standard format string)|, to define the overall format of the result string.| -|"f" (full date / short time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| -|"F" (full date / long time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| -|"g" (general date / short time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| -|"G" (general date / long time; standard format string)|, to define the format of the date component of the result string.

, to define the format of the time component of the result string.| -|"M", "m" (month/day; standard format string)|, to define the overall format of the result string.| -|"O", "o" (round-trip date/time; standard format string)|None.| -|"R", "r" (RFC1123; standard format string)|, to define a result string that conforms to the RFC 1123 standard. The property is read-only.| -|"s" (sortable date/time; standard format string)|, to define a result string that conforms to the ISO 8601 standard. The property is read-only.| -|"t" (short time; standard format string)|, to define the overall format of the result string.| -|"T" (long time; standard format string)|, to define the overall format of the result string.| -|"u" (universal sortable date/time; standard format string)|, to define a result string that conforms to the ISO 8601 standard for coordinated universal time. The property is read-only.| -|"U" (universal full date/time; standard format string)|, to define the overall format of the result string.| -|"Y", "y" (year month; standard format string)|, to define the overall format of the result string.| -|"ddd" (custom format specifier)|, to include the abbreviated name of the day of the week in the result string.| -|"g", "gg" (custom format specifier)|Calls the method to insert the era name in the result string.| -|"MMM" (custom format specifier)| or , to include the abbreviated month name in the result string.| -|"MMMM" (custom format specifier)| or , to include the full month name in the result string.| -|"t" (custom format specifier)| or , to include the first character of the AM/PM designator in the result string.| -|"tt" (custom format specifier)| or , to include the full AM/PM designator in the result string.| -|":" (custom format specifier)|, to include the time separator in the result string.| -|"/" (custom format specifier)|, to include the date separator in the result string.| - -## Modify DateTimeFormatInfo properties - -You can change the result string produced by date and time format strings by modifying the associated properties of a writable object. To determine if a object is writable, use the property. To customize a object in this way: - -1. Create a read/write copy of a object whose formatting conventions you want to modify. - -2. Modify the property or properties that are used to produce the desired result string. (For information about how formatting methods use properties to define result strings, see the previous section, [Format strings and DateTimeFormatInfo properties](#format-strings-and-datetimeformatinfo-properties).) - -3. Use the custom object you created as the argument in calls to formatting methods. - -There are two other ways to change the format of a result string: - -- You can use the class to define either a custom culture (a culture that has a unique name and that supplements existing cultures) or a replacement culture (one that is used instead of a specific culture). You can save and access this culture programmatically as you would any object supported by .NET. - -- If the result string is not culture-sensitive and doesn't follow a predefined format, you can use a custom date and time format string. For example, if you are serializing date and time data in the format YYYYMMDDHHmmss, you can generate the result string by passing the custom format string to the method, and you can convert the result string back to a value by calling the method. - -### Change the short date pattern - -The following example changes the format of a result string produced by the "d" (short date) standard format string. It changes the associated property for the en-US or English (United States) culture from its default of "M/d/yyyy" to "yyyy'-"MM"-"dd" and uses the "d" standard format string to display the date both before and after the property is changed. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example1.cs" id="Snippet10"::: - -### Change the date separator character - -The following example changes the date separator character in a object that represents the formatting conventions of the fr-FR culture. The example uses the "g" standard format string to display the date both before and after the property is changed. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example3.cs" id="Snippet12"::: - -### Change day name abbreviations and the long date pattern - -In some cases, the long date pattern, which typically displays the full day and month name along with the number of the day of the month and the year, may be too long. The following example shortens the long date pattern for the en-US culture to return a one-character or two-character day name abbreviation followed by the day number, the month name abbreviation, and the year. It does this by assigning shorter day name abbreviations to the array, and by modifying the custom format string assigned to the property. This affects the result strings returned by the "D" and "f" standard format strings. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example2.cs" id="Snippet13"::: - -Ordinarily, the change to the property also affects the property, which in turn defines the result string returned by the "F" standard format string. To preserve the original full date and time pattern, the example reassigns the original custom format string assigned to the property after the property is modified. - -### Change from a 12-hour clock to a 24-hour clock - -For many cultures in .NET, the time is expressed by using a 12-hour clock and an AM/PM designator. The following example defines a `ReplaceWith24HourClock` method that replaces any time format that uses a 12-hour clock with a format that uses a 24-hour clock. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example5.cs" id="Snippet14"::: - -The example uses a regular expression to modify the format string. The regular expression pattern `@"^(?\s*t+\s*)? (?(openAMPM) h+(?[^ht]+)$ | \s*h+(?[^ht]+)\s*t+)` is defined as follows: - -|Pattern|Description| -|-------------|-----------------| -|`^`|Begin the match at the beginning of the string.| -|`(?\s*t+\s*)?`|Match zero or one occurrence of zero or more white-space characters, followed by the letter "t" one or more times, followed by zero or more white-space characters. This capturing group is named `openAMPM`.| -|`(?(openAMPM) h+(?[^ht]+)$`|If the `openAMPM` group has a match, match the letter "h" one or more times, followed by one or more characters that are neither "h" nor "t". The match ends at the end of the string. All characters captured after "h" are included in a capturing group named `nonHours`.| -|`| \s*h+(?[^ht]+)\s*t+)`|If the `openAMPM` group does not have a match, match the letter "h" one or more times, followed by one or more characters that are neither "h" nor "t", followed by zero or more white-space characters. Finally, match one or more occurrences of the letter "t". All characters captured after "h" and before the white-spaces and "t" are included in a capturing group named `nonHours`.| - -The `nonHours` capturing group contains the minute and possibly the second component of a custom date and time format string, along with any time separator symbols. The replacement pattern `HH${nonHours}` prepends the substring "HH" to these elements. - -### Display and change the era in a date - -The following example adds the "g" custom format specifier to the property of an object that represents the formatting conventions of the en-US culture. This addition affects the following three standard format strings: - -- The "D" (long date) standard format string, which maps directly to the property. - -- The "f" (full date / short time) standard format string, which produces a result string that concatenates the substrings produced by the and properties. - -- The "F" (full date / long time) standard format string, which maps directly to the property. Because we have not explicitly set this property value, it is generated dynamically by concatenating the and properties. - -The example also shows how to change the era name for a culture whose calendar has a single era. In this case, the en-US culture uses the Gregorian calendar, which is represented by a object. The class supports a single era, which it names A.D. (Anno Domini). The example changes the era name to C.E. (Common Era) by replacing the "g" custom format specifier in the format string assigned to the property with a literal string. The use of a literal string is necessary, because the era name is typically returned by the method from private data in the culture tables supplied by either .NET or the operating system. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/example4.cs" id="Snippet11"::: - -## Parse date and time strings - -Parsing involves converting the string representation of a date and time to a or value. Both of these types include the `Parse`, `TryParse`, `ParseExact`, and `TryParseExact` methods to support parsing operations. The `Parse` and `TryParse` methods convert a string that can have a variety of formats, whereas `ParseExact` and `TryParseExact` require that the string have a defined format or formats. If the parsing operation fails, `Parse` and `ParseExact` throw an exception, whereas `TryParse` and `TryParseExact` return `false`. - -The parsing methods implicitly or explicitly use a enumeration value to determine which style elements (such as leading, trailing, or inner white space) can be present in the string to be parsed, and how to interpret the parsed string or any missing elements. If you don't provide a value when you call the `Parse` or `TryParse` method, the default is , which is a composite style that includes the , , and flags. For the `ParseExact` and `TryParseExact` methods, the default is ; the input string must correspond precisely to a particular custom date and time format string. - -The parsing methods also implicitly or explicitly use a object that defines the specific symbols and patterns that can occur in the string to be parsed. If you don't provide a object, the object for the current culture is used by default. For more information about parsing date and time strings, see the individual parsing methods, such as , , , and . - -The following example illustrates the culture-sensitive nature of parsing date and time strings. It tries to parse two date strings by using the conventions of the en-US, en-GB, fr-FR, and fi-FI cultures. The date that is interpreted as 8/18/2014 in the en-US culture throws a exception in the other three cultures because 18 is interpreted as the month number. 1/2/2015 is parsed as the second day of the first month in the en-US culture, but as the first day of the second month in the remaining cultures. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/parse1.cs" id="Snippet15"::: - -Date and time strings are typically parsed for two reasons: - -- To convert user input into a date and time value. -- To round-trip a date and time value; that is, to deserialize a date and time value that was previously serialized as a string. - -The following sections discuss these two operations in greater detail. - -### Parse user strings - -When you parse date and time strings input by the user, you should always instantiate a object that reflects the user's cultural settings, including any customizations the user may have made. Otherwise, the date and time object may have incorrect values. For information about how to instantiate a object that reflects user cultural customizations, see the [DateTimeFormatInfo and dynamic data](#datetimeformatinfo-and-dynamic-data) section. - -The following example illustrates the difference between a parsing operation that reflects user cultural settings and one that does not. In this case, the default system culture is en-US, but the user has used Control Panel, **Region and Language** to change the short date pattern from its default of "M/d/yyyy" to "yy/MM/dd". When the user enters a string that reflects user settings, and the string is parsed by a object that also reflects user settings (overrides), the parsing operation returns a correct result. However, when the string is parsed by a object that reflects standard en-US cultural settings, the parsing method throws a exception because it interprets 14 as the number of the month, not the last two digits of the year. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/parse2.cs" id="Snippet16"::: - -### Serialize and deserialize date and time data - -Serialized date and time data are expected to round-trip; that is, all serialized and deserialized values should be identical. If a date and time value represents a single moment in time, the deserialized value should represent the same moment in time regardless of the culture or time zone of the system on which it was restored. To round-trip date and time data successfully, you must use the conventions of the invariant culture, which is returned by the property, to generate and parse the data. The formatting and parsing operations should never reflect the conventions of the default culture. If you use default cultural settings, the portability of the data is strictly limited; it can be successfully deserialized only on a thread whose cultural-specific settings are identical to those of the thread on which it was serialized. In some cases, this means that the data cannot even be successfully serialized and deserialized on the same system. - -If the time component of a date and time value is significant, it should also be converted to UTC and serialized by using the "o" or "r" [standard format string](../../standard/base-types/standard-date-and-time-format-strings.md). The time data can then be restored by calling a parsing method and passing it the appropriate format string along with the invariant culture as the `provider` argument. - -The following example illustrates the process of round-tripping a date and time value. It serializes a date and time on a system that observes U.S. Pacific time and whose current culture is en-US. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/serialize1.cs" id="Snippet17"::: - -It deserializes the data on a system in the Brussels, Copenhagen, Madrid and Paris time zone and whose current culture is fr-FR. The restored date is nine hours later than the original date, which reflects the time zone adjustment from eight hours behind UTC to one hour ahead of UTC. Both the original date and the restored date represent the same moment in time. - -:::code language="csharp" source="./snippets/System.Globalization/DateTimeFormatInfo/csharp/serialize2.cs" id="Snippet18"::: diff --git a/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md b/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md deleted file mode 100644 index ba0c41f1c1443..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-numberformatinfo.md +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: System.Globalization.NumberFormatInfo class -description: Learn more about the System.Globalization.NumberFormatInfo class. -ms.date: 12/28/2023 -ms.topic: concept-article ---- -# class - -[!INCLUDE [context](includes/context.md)] - -The class contains culture-specific information that is used when you format and parse numeric values. This information includes the currency symbol, the decimal symbol, the group separator symbol, and the symbols for positive and negative signs. - -## Instantiate a NumberFormatInfo object - -You can instantiate a object that represents the formatting conventions of the current culture, the invariant culture, a specific culture, or a neutral culture. - -### Instantiate a NumberFormatInfo object for the current culture - -You can instantiate a object for the current culture in any of the following ways. In each case, the returned object is read-only. - -- By retrieving a object that represents the current culture from the property, and retrieving the object from its property. - -- By retrieving the object returned by the `static` (`Shared` in Visual Basic) property. - -- By calling the method with a object that represents the current culture. - -The following example uses these three ways to create objects that represent the formatting conventions of the current culture. It also retrieves the value of the property to illustrate that each object is read-only. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/instantiate1.cs" id="Snippet1"::: - -You can create a writable object that represents the conventions of the current culture in any of the following ways: - -- By retrieving a object in any of the ways illustrated in the previous code example, and calling the method on the returned object. This creates a copy of the original object, except that its property is `false`. - -- By calling the method to create a object that represents the current culture, and then using its property to retrieve the object. - -The following example illustrates these two ways of instantiating a object, and displays the value of its property to illustrate that the object is not read-only. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/instantiate2.cs" id="Snippet2"::: - -Note that the Windows operating system allows the user to override some of the property values used in numeric formatting and parsing operations through the **Region and Language** item in Control Panel. For example, a user whose culture is English (United States) might choose to display currency values as 1.1 USD instead of the default of $1.1. The objects retrieved in the ways discussed previously all reflect these user overrides. If this is undesirable, you can create a object that does not reflect user overrides (and that is also read/write rather than read-only) by calling the constructor and supplying a value of `false` for the `useUserOverride` argument. The following example provides an illustration for a system whose current culture is English (United States) and whose currency symbol has been changed from the default of $ to USD. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/instantiate3.cs" id="Snippet3"::: - -If the property is set to `true`, the properties , , and are also retrieved from the user settings. If the user settings are incompatible with the culture associated with the object (for example, if the selected calendar is not one of the calendars listed by the property), the results of the methods and the values of the properties are undefined. - -### Instantiate a NumberFormatInfo object for the invariant culture - -The invariant culture represents a culture that is culture-insensitive. It is based on the English language but not on any specific English-speaking country/region. Although the data of specific cultures can be dynamic and can change to reflect new cultural conventions or user preferences, the data of the invariant culture does not change. A object that represents the formatting conventions of the invariant culture can be used for formatting operations in which result strings should not vary by culture. - -You can instantiate a object that represents the formatting conventions of the invariant culture in the following ways: - -- By retrieving the value of the property. The returned object is read-only. - -- By retrieving the value of the property from the object that is returned by the property. The returned object is read-only. - -- By calling the parameterless class constructor. The returned object is read/write. - -The following example uses each of these methods to instantiate a object that represents the invariant culture. It then indicates whether the object is read-only, - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/instantiate4.cs" id="Snippet4"::: - -### Instantiate a NumberFormatInfo object for a specific culture - -A specific culture represents a language that is spoken in a particular country/region. For example, en-US is a specific culture that represents the English language spoken in the United States, and en-CA is a specific culture that represents the English language spoken in Canada. You can instantiate a object that represents the formatting conventions of a specific culture in the following ways: - -- By calling the method and retrieving the value of the returned object's property. The returned object is read-only. - -- By passing a object that represents the culture whose object you want to retrieve to the static method. The returned object is read/write. - -- By calling the method and retrieving the value of the returned object's property. The returned object is read/write. - -- By calling one of the class constructors and retrieving the value of the returned object's property. The returned object is read/write. - -The following example uses these four ways to create a object that reflects the formatting conventions of the Indonesian (Indonesia) culture. It also indicates whether each object is read-only. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/instantiate5.cs" id="Snippet5"::: - -### Instantiate a NumberFormatInfo object for a neutral culture - -A neutral culture represents a culture or language that is independent of a country/region. It is typically the parent of one or more specific cultures. For example, fr is a neutral culture for the French language and the parent of the fr-FR culture. You create a object that represents the formatting conventions of a neutral culture in the same way that you create a object that represents the formatting conventions of a specific culture. - -However, because it is independent of a specific country/region, a neutral culture lacks culture-specific formatting information. Rather than populating the object with generic values, .NET returns a object that reflects the formatting conventions of a specific culture that is a child of the neutral culture. For example, the object for the neutral en culture reflects the formatting conventions of the en-US culture, and the object for the fr culture reflects the formatting conventions of the fr-FR culture. - -You can use code like the following to determine which specific culture's formatting conventions each neutral culture represents. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/instantiate6.cs" id="Snippet6"::: - -## Dynamic data - -The culture-specific data for formatting numeric values provided by the class is dynamic, just like the cultural data provided by the class. You should not make any assumptions about the stability of values for objects that are associated with particular objects. Only the data provided by the invariant culture and its associated object is stable. Other data can change between application sessions, or even within a single session, for the following reasons: - -- **System updates.** Cultural preferences such as the currency symbol or currency formats change over time. When this happens, Windows Update includes changes to the property value for a particular culture. - -- **Replacement cultures.** The class can be used to replace the data of an existing culture. - -- **Cascading changes to property values.** A number of culture-related properties can change at runtime, which, in turn, causes data to change. For example, the current culture can be changed either programmatically or through user action. When this happens, the object returned by the property changes to an object associated with the current culture. - -- **User preferences.** Users of your application might override some of the values associated with the current system culture through the region and language options in Control Panel. For example, users might choose a different currency symbol or a different decimal separator symbol. If the property is set to `true` (its default value), the properties of the object are also retrieved from the user settings. - -All user-overridable properties of a object are initialized when the object is created. There is still a possibility of inconsistency, because neither object creation nor the user override process is atomic, and the relevant values may change during object creation. However, these inconsistencies should be extremely rare. - -You can control whether user overrides are reflected in objects that represent the same culture as the current culture. The following table lists the ways in which a object can be retrieved and indicates whether the resulting object reflects user overrides. - -|Source of CultureInfo and NumberFormatInfo object|Reflects user overrides| -|-------------------------------------------------------|-----------------------------| -|`CultureInfo.CurrentCulture.NumberFormat` property|Yes| -| property|Yes| -| method|Yes| -| method|No| -| constructor|Yes| -| constructor|Depends on value of `useUserOverride` parameter| - -Unless there is a compelling reason to do otherwise, you should respect user overrides when you use the object in client applications to format and parse user input or to display numeric data. For server applications or unattended applications, you should not respect user overrides. However, if you are using the object either explicitly or implicitly to persist numeric data in string form, you should either use a object that reflects the formatting conventions of the invariant culture, or you should specify a custom numeric format string that you use regardless of culture. - -## IFormatProvider, NumberFormatInfo, and numeric formatting - -A object is used implicitly or explicitly in all numeric formatting operations. These include calls to the following methods: - -- All numeric formatting methods, such as , , and . - -- The major composite formatting method, . - -- Other composite formatting methods, such as and . - -All numeric formatting operations make use of an implementation. The interface includes a single method, . This is a callback method that is passed a object that represents the type needed to provide formatting information. The method is responsible for returning either an instance of that type or `null`, if it cannot provide an instance of the type. .NET provides two implementations for formatting numbers: - -- The class, which represents a specific culture (or a specific language in a specific country/region). In a numeric formatting operation, the method returns the object associated with its property. - -- The class, which provides information about the formatting conventions of its associated culture. The method returns an instance of itself. - -If an implementation is not provided to a formatting method explicitly, a object returned by the property that represents the current culture is used. - -The following example illustrates the relationship between the interface and the class in formatting operations by defining a custom implementation. Its method displays the type name of the object requested by the formatting operation. If the interface is requesting a object, this method provides the object for the current culture. As the output from the example shows, the method requests a object to provide formatting information, whereas the method requests and objects as well as an implementation. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/formatprovider1.cs" id="Snippet1"::: - -If an implementation is not explicitly provided in a numeric formatting method call, the method calls the `CultureInfo.CurrentCulture.GetFormat` method, which returns the object that corresponds to the current culture. - -## Format strings and NumberFormatInfo properties - -Every formatting operation uses either a standard or a custom numeric format string to produce a result string from a number. In some cases, the use of a format string to produce a result string is explicit, as in the following example. This code calls the method to convert a value to a number of different string representations by using the formatting conventions of the en-US culture. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/properties1.cs" id="Snippet2"::: - -In other cases, the use of a format string is implicit. For example, in the following method calls to the default or parameterless method, the value of the instance is formatted by using the general ("G") format specifier and the conventions of the current culture, which in this case is the en-US culture. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/properties2.cs" id="Snippet3"::: - -Each standard numeric format string uses one or more properties to determine the pattern or the symbols used in the result string. Similarly, each custom numeric format specifier except "0" and "#" insert symbols in the result string that are defined by properties. The following table lists the standard and custom numeric format specifiers and their associated properties. To change the appearance of the result string for a particular culture, see the [Modify NumberFormatInfo properties](#modify-numberformatinfo-properties) section. For details about the use of these format specifiers, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md). - -|Format specifier|Associated properties| -|----------------------|---------------------------| -|"C" or "c" (currency format specifier)|, to define the default number of fractional digits.

, to define the decimal separator symbol.

, to define the group or thousands separator.

, to define the sizes of integral groups.

, to define the pattern of negative currency values.

, to define the pattern of positive currency values.

, to define the currency symbol.

, to define the negative sign symbol.| -|"D" or "d" (decimal format specifier)|, to define the negative sign symbol.| -|"E" or "e" (exponential or scientific format specifier)|, to define the negative sign symbol in the mantissa and exponent.

, to define the decimal separator symbol.

, to define the positive sign symbol in the exponent.| -|"F" or "f" (fixed-point format specifier)|, to define the negative sign symbol.

, to define the default number of fractional digits.

, to define the decimal separator symbol.| -|"G" or "g" (general format specifier)|, to define the negative sign symbol.

, to define the decimal separator symbol.

, to define the positive sign symbol for result strings in exponential format.| -|"N" or "n" (number format specifier)|, to define the negative sign symbol.

, to define the default number of fractional digits.

, to define the decimal separator symbol.

, to define the group separator (thousands) symbol.

, to define the number of integral digits in a group.

, to define the format of negative values.| -|"P" or "p" (percent format specifier)|, to define the negative sign symbol.

, to define the default number of fractional digits.

, to define the decimal separator symbol.

, to define the group separator symbol.

, to define the number of integral digits in a group.

, to define the placement of the percent symbol and the negative symbol for negative values.

, to define the placement of the percent symbol for positive values.

, to define the percent symbol.| -|"R" or "r" (round-trip format specifier)|, to define the negative sign symbol.

, to define the decimal separator symbol.

, to define the positive sign symbol in an exponent.| -|"X" or "x" (hexadecimal format specifier)|None.| -|"." (decimal point custom format specifier)|, to define the decimal separator symbol.| -|"," (group separator custom format specifier)|, to define the group (thousands) separator symbol.| -|"%" (percentage placeholder custom format specifier)|, to define the percent symbol.| -|"‰" (per mille placeholder custom format specifier)|, to define the per mille symbol.| -|"E" (exponential notation custom format specifier)|, to define the negative sign symbol in the mantissa and exponent.

, to define the positive sign symbol in the exponent.| - -Note that the class includes a property that specifies the base 10 digits used by a specific culture. However, the property is not used in formatting operations; only the Basic Latin digits 0 (U+0030) through 9 (U+0039) are used in the result string. In addition, for and values of `NaN`, `PositiveInfinity`, and `NegativeInfinity`, the result string consists exclusively of the symbols defined by the , , and properties, respectively. - -## Modify NumberFormatInfo properties - -You can modify the properties of a object to customize the result string produced in a numeric formatting operation. To do this: - -1. Create a read/write copy of a object whose formatting conventions you want to modify. For more information, see the [Instantiate a NumberFormatInfo object](#instantiate-a-numberformatinfo-object) section. - -2. Modify the property or properties that are used to produce the desired result string. For information about how formatting methods use properties to define result strings, see the [Format strings and NumberFormatInfo properties](#format-strings-and-numberformatinfo-properties) section. - -3. Use the custom object as the argument in calls to formatting methods. - -> [!NOTE] -> Instead of dynamically modifying a culture's property values each time an application is started, you can use the class to define either a custom culture (a culture that has a unique name and that supplements existing cultures) or a replacement culture (one that is used instead of a specific culture). - -The following sections provide some examples. - -### Modify the currency symbol and pattern - -The following example modifies a object that represents the formatting conventions of the en-US culture. It assigns the ISO-4217 currency symbol to the property and defines a pattern for currency values that consists of the currency symbol followed by a space and a numeric value. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/customize_currency1.cs" id="Snippet1"::: - -### Format a national identification number - -Many national identification numbers consist exclusively of digits and so can easily be formatted by modifying the properties of a object. For example, a social security number in the United States consists of 9 digits arranged as follows: `XXX-XX-XXXX`. The following example assumes that social security numbers are stored as integer values and formats them appropriately. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/customize_ssn1.cs" id="Snippet2"::: - -## Parse numeric strings - -Parsing involves converting the string representation of a number to a number. Each numeric type in .NET includes two overloaded parsing methods: `Parse` and `TryParse`. The `Parse` method converts a string to a number and throws an exception if the conversion fails. The `TryParse` method converts a string to a number, assigns the number to an `out` argument, and returns a value that indicates whether the conversion succeeded. - -The parsing methods implicitly or explicitly use a enumeration value to determine what style elements (such as group separators, a decimal separator, or a currency symbol) can be present in a string if the parsing operation is to succeed. If a value is not provided in the method call, the default is a value that includes the and flags, which specifies that the parsed string can include group symbols, a decimal separator, a negative sign, and white-space characters, or it can be the string representation of a number in exponential notation. - -The parsing methods also implicitly or explicitly use a object that defines the specific symbols and patterns that can occur in the string to be parsed. If a object is not provided, the default is the for the current culture. For more information about parsing, see the individual parsing methods, such as , , , , , and . - -The following example illustrates the culture-sensitive nature of parsing strings. It tries to parse a string that include thousands separators by using the conventions of the en-US, fr-FR, and invariant cultures. A string that includes the comma as a group separator and the period as a decimal separator fails to parse in the fr-FR culture, and a string with white space as a group separator and a comma as a decimal separator fails to parse in the en-US and invariant cultures. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/parse1.cs" id="Snippet4"::: - -Parsing generally occurs in two contexts: - -- As an operation that is designed to convert user input into a numeric value. - -- As an operation that is designed to round-trip a numeric value; that is, to deserialize a numeric value that was previously serialized as a string. - -The following sections discuss these two operations in greater detail. - -### Parse user strings - -When you are parsing numeric strings input by the user, you should always instantiate a object that reflects the user's cultural settings. For information about how to instantiate a object that reflects user customizations, see the [Dynamic data](#dynamic-data) section. - -The following example illustrates the difference between a parsing operation that reflects user cultural settings and one that does not. In this case, the default system culture is en-US, but the user has defined "," as the decimal symbol and "." as the group separator in Control Panel, **Region and Language**. Ordinarily, these symbols are reversed in the default en-US culture. When the user enters a string that reflects user settings, and the string is parsed by a object that also reflects user settings (overrides), the parsing operation returns a correct result. However, when the string is parsed by a object that reflects standard en-US cultural settings, it mistakes the comma symbol for a group separator and returns an incorrect result. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/parseuser1.cs" id="Snippet5"::: - -### Serialize and deserialize numeric data - -When numeric data is serialized in string format and later deserialized and parsed, the strings should be generated and parsed by using the conventions of the invariant culture. The formatting and parsing operations should never reflect the conventions of a specific culture. If culture-specific settings are used, the portability of the data is strictly limited; it can be successfully deserialized only on a thread whose culture-specific settings are identical to those of the thread on which it was serialized. In some cases, this means that the data cannot even be successfully deserialized on the same system on which it was serialized. - -The following example illustrates what can happen when this principle is violated. Floating-point values in an array are converted to strings when the current thread uses the culture-specific settings of the en-US culture. -The data is then parsed by a thread that uses the culture-specific settings of the pt-BR culture. In this case, although each parsing operation succeeds, the data doesn't round-trip successfully and data corruption occurs. -In other cases, a parsing operation could fail and a exception could be thrown. - -:::code language="csharp" source="./snippets/System.Globalization/NumberFormatInfo/csharp/parsepersisted.cs" id="Snippet6"::: diff --git a/docs/fundamentals/runtime-libraries/system-globalization-persiancalendar.md b/docs/fundamentals/runtime-libraries/system-globalization-persiancalendar.md deleted file mode 100644 index 7ecf67746eef4..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-persiancalendar.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: System.Globalization.PersianCalendar class -description: Learn more about the System.Globalization.PersianCalendar class. -ms.date: 04/09/2025 -ms.topic: concept-article ---- -# class - -[!INCLUDE [context](includes/context.md)] - -The Persian calendar is used in most countries/regions where Persian is spoken, although some regions use different month names. The Persian calendar is the official calendar of Iran and Afghanistan, and it is one of the alternative calendars in regions such as Kazakhstan and Tajikistan. - -> [!NOTE] -> For information about using the class and the other calendar classes in .NET, see [Working with Calendars](../../standard/datetime/working-with-calendars.md). - -The Persian calendar is a solar Hijri calendar, and starts from the year of the Hijra, which corresponds to 622 C.E. the year when Muhammad (PBUH) migrated from Mecca to Medina. - -The Persian calendar is based on a solar year and is approximately 365 days long. A year cycles through four seasons, and a new year begins when the sun appears to cross the equator from the southern hemisphere to the northern hemisphere as viewed from the center of the Earth. The new year marks the first day of the month of Farvardeen, which is the first day of spring in the northern hemisphere. For example, the date March 21, 2002 C.E. corresponds to the first day of the month of Farvardeen in the year 1381 Anno Persico. - -Each of the first six months in the Persian calendar has 31 days, each of the next five months has 30 days, and the last month has 29 days in a common year and 30 days in a leap year. A leap year is a year that, when divided by 33, has a remainder of 1, 5, 9, 13, 17, 22, 26, or 30. For example, the year 1370 is a leap year because dividing it by 33 yields a remainder of 17. There are approximately eight leap years in every 33-year cycle. - -## The PersianCalendar class and .NET versions - -Starting with .NET Framework 4.6, the class uses the Hijri solar astronomical algorithm rather than an observational algorithm to calculate dates. This makes the implementation consistent with the Persian calendar in use in Iran and Afghanistan, the two countries in which the Persian calendar is in most widespread use. The change affects all apps running on .NET Framework 4 or later if .NET Framework 4.6 is installed. - -As a result of the changed algorithm: - -- The two algorithms should return identical results when converting dates between 1800 and 2123 in the Gregorian calendar. -- The two algorithms might return different results when converting dates before 1800 and after 2123 in the Gregorian calendar. -- The property value has changed from March 21, 0622 in the Gregorian calendar to March 22, 0622 in the Gregorian calendar. -- The property value has changed from the 10th day of the 10th month of the year 9378 in the Persian calendar to the 13th day of the 10th month of the year 9378 in the Persian calendar. -- The method might return a different result than it did previously. - -## Use the PersianCalendar class - -You can use a object to calculate dates in the Persian calendar or convert Persian dates to and from Gregorian dates. The Persian calendar is the [default calendar](xref:System.Globalization.CultureInfo.Calendar) for cultures such as Persian (Afghanistan) and Central Kurdish (Iran). diff --git a/docs/fundamentals/runtime-libraries/system-globalization-regioninfo.md b/docs/fundamentals/runtime-libraries/system-globalization-regioninfo.md deleted file mode 100644 index e75dd5afb822e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-regioninfo.md +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: System.Globalization.RegionInfo class -description: Learn more about the System.Globalization.RegionInfo class. -ms.date: 12/28/2023 -ms.topic: concept-article ---- -# class - -[!INCLUDE [context](includes/context.md)] - -Unlike the class, the class does not represent user preferences and does not depend on the user's language or culture. - -## Names associated with a RegionInfo object - -The name of a object is one of the two-letter codes defined in ISO 3166 for country/region. Case is not significant. The , , and properties return the appropriate codes in uppercase. For the current list of names, see [ISO 3166: Country codes](https://www.iso.org/iso-3166-country-codes.html). - -## Instantiate a RegionInfo object - -To instantiate a object, you pass the constructor either a two-letter region name, such as "US" for the United States, or the name of a specific culture, such as "en-US" for English (United States). However, we recommend that you use a specific culture name instead of a two-letter region name, because a object is not completely language-independent. Several properties, including , , and , depend on culture names. - -The following example illustrates the difference in property values for three objects that represent Belgium. The first is instantiated from a region name (`BE`) only, while the second and third are instantiated from culture names (`fr-BE` for French (Belgium) and `nl-BE` for Dutch (Belgium), respectively). The example uses reflection to retrieve the property values of each object. - -:::code language="csharp" source="./snippets/System.Globalization/RegionInfo/csharp/propertyvalues1.cs" id="Snippet2"::: - -In scenarios such as the following, use culture names instead of country/region names when you instantiate a object: - -- When the language name is of primary importance. For example, for the `es-US` culture name, you'll probably want your application to display "Estados Unidos" instead of "United States". Using the country/region name (`US`) alone yields "United States" regardless of the language, so you should work with the culture name instead. - -- When script differences must be considered. For example, the country/region `AZ` deals with Azerbaijani cultures that have the names `az-Latn-AZ` and `az-Cyrl-AZ`, and the Latin and Cyrillic scripts can be very different for this country/region. - -- When maintenance of detail is important. The values returned by members can differ depending on whether the object was instantiated by using a culture name or a region name. For example, the following table lists the differences in return values when a object is instantiated by using the "US" region, the "en-US" culture, and the "es-US" culture. - - | Member | "US" | "en-US" | "es-US" | - |-----------------------------------------------------------|-----------------|-----------------|-------------------| - | | `US Dollar` | `US Dollar` | `Dólar de EE.UU.` | - | | `US` | `en-US` | `es-US` | - | | `United States` | `United States` | `Estados Unidos` | - | | `US` | `en-US` | `es-US` | diff --git a/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md b/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md deleted file mode 100644 index 74d5987ea8a7f..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-sortkey.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: System.Globalization.SortKey class -description: Learn more about the System.Globalization.SortKey class. -ms.date: 12/28/2023 -ms.topic: concept-article ---- -# class - -[!INCLUDE [context](includes/context.md)] - -A culture-sensitive comparison of two strings depends on each character in the strings having several categories of sort weights, including script, alphabetic, case, and diacritic weights. A sort key serves as the repository of these weights for a particular string. - -The method returns an instance of the class that reflects the culture-sensitive mapping of characters in a specified string. The value of a object is its key data, which is returned by the property. This key data consists of a series of bytes that encode the string, culture-specific sorting rules, and user-specified comparison options. A comparison using sort keys consists of a bitwise comparison of the corresponding key data in each sort key. For example, if you create a sort key by calling the method with a value of , a string comparison operation that uses the sort key is case-insensitive. - -After you create a sort key for a string, you compare sort keys by calling the static method. This method performs a simple byte-by-byte comparison, so it is much faster than the or method. - -> [!NOTE] -> You can download the [Sorting Weight Tables](https://www.microsoft.com/download/details.aspx?id=10921), a set of text files that contain information on the character weights used in sorting and comparison operations for Windows operating systems, the [Default Unicode Collation Element Table](https://www.unicode.org/Public/UCA/latest/allkeys.txt), the sort weight table for Linux and macOS. - -## Performance considerations - -When performing a string comparison, the and methods yield the same results, but they target different scenarios. - -At a high level, the method generates the sort key for each string, performs the comparison, and then discards the sort key and returns the result of the comparison. However, the method actually doesn't generate an entire sort key to perform the comparison. Instead, the method generates the key data for each text element (that is, base character, surrogate pair, or combining character sequence) in each string. The method then compares the key data for the corresponding text elements. The operation terminates as soon as the ultimate result of the comparison is determined. Sort key information is computed, but no object is created. This strategy is economical in terms of performance if both strings are compared once, but becomes expensive if the same strings are compared many times. - -The method requires generation of a object for each string before performing the comparison. This strategy is expensive in terms of performance for the first comparison because of the time and memory invested to generate the objects. However, it becomes economical if the same sort keys are compared many times. - -For example, suppose you write an application that searches a database table for the row in which the string-based index column matches a specified search string. The table contains thousands of rows, and comparing the search string to the index in each row will take a long time. Therefore, when the application stores a row and its index column, it also generates and stores the sort key for the index in a column dedicated to improving search performance. When the application searches for a target row, it compares the sort key for the search string to the sort key for the index string, instead of comparing the search string to the index string. - -## Security considerations - -The method returns a object with the value based on a specified string and value, and the culture associated with the underlying object. If a security decision depends on a string comparison or case change, you should use the method of the invariant culture to ensure that the behavior of the operation is consistent, regardless of the culture settings of the operating system. - -Use the following steps to obtain a sort key: - -1. Retrieve the invariant culture from the property. - -2. Retrieve a object for the invariant culture from the property. - -3. Call the method. - -Working with the value of a object is equivalent to calling the Windows `LCMapString` method with the LCMAP_SORTKEY value specified. However, for the object, the sort keys for English characters precede the sort keys for Korean characters. - - objects can be serialized, but only so that they can cross objects. If an application serializes a object, the application must regenerate all the sort keys when there is a new version of .NET. - -For more information about sort keys, see Unicode Technical Standard #10, "Unicode Collation Algorithm" on the [Unicode Consortium website](https://go.microsoft.com/fwlink/?linkid=37123). diff --git a/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md b/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md deleted file mode 100644 index e862632042267..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-globalization-sortversion.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: System.Globalization.SortVersion class -description: Learn more about the System.Globalization.SortVersion class. -ms.date: 12/28/2023 -ms.topic: concept-article ---- -# class - -[!INCLUDE [context](includes/context.md)] - -## Sorting and string comparison in .NET Framework - -Through .NET Framework 4, each version of .NET Framework included tables that contained sort weights and data on string normalization and that are based on a particular version of Unicode. In .NET Framework 4.5 and later versions, the presence of these tables depends on the operating system: - -- On Windows 7 and previous versions, the tables continue to be used for comparing and ordering strings. -- On Windows 8, .NET Framework delegates string comparison and ordering operations to the operating system. - -Consequently, the result of a string comparison can depend not only on .NET Framework version, but also on the operating system version, as the following table shows. Note that this list of supported Unicode versions applies to character comparison and sorting only; it does not apply to classification of Unicode characters by category. - -| .NET Framework version | Operating system | Unicode version | -|------------------------|------------------------------|-----------------| -| 4 | All operating systems | Unicode 5.0 | -| 4.5 and later versions | Windows 7 | Unicode 5.0 | -| 4.5 and later versions | Windows 8 and later versions | Unicode 6.0 | - -On Windows 8, because the version of Unicode used in string comparison and ordering depends on the version of the operating system, the results of string comparison may differ even for applications that run on a specific version of .NET Framework. - -## Sorting and string comparison in .NET Core - -All versions of .NET (Core) rely on the underlying operating system when performing string comparisons. Therefore, the results of a string comparison or the order in which strings are sorted depends on the version of Unicode used by the operating system when performing the comparison. On Linux, macOS, and Windows 10 and later versions, [International Components for Unicode](https://icu.unicode.org/) libraries provide the implementation for comparison and sorting APIs. - -## Use the SortVersion class - -The class provides information about the Unicode version used by .NET for string comparison and ordering. It enables developers to write applications that can detect and successfully handle changes in the version of Unicode that is used to compare and sort an application's strings. - -You can instantiate a object in two ways: - -- By calling the constructor, which instantiates a new object based on a version number and sort ID. This constructor is most useful when recreating a object from saved data. -- By retrieving the value of the property. This property provides information about the Unicode version used by the .NET implementation on which the application is running. - -The class has two properties, and , that indicate the Unicode version and the specific culture used for string comparison. The property is an arbitrary numeric value that reflects the Unicode version used for string comparison, and the property is an arbitrary that reflects the culture whose conventions are used for string comparison. The values of these two properties are important only when you compare two objects by using the method, the operator, or the operator. - -You typically use a object when saving or retrieving some form of culture-sensitive, ordered string data, such as indexes or the literal strings themselves. This requires the following steps: - -1. When the ordered string data is saved, the and property values are also saved. - -2. When the ordered string data is retrieved, you can recreate the object used for ordering the strings by calling the constructor. - -3. This newly instantiated object is compared with a object that reflects the culture whose conventions are used to order the string data. - -4. If the two objects are not equal, the string data must be reordered. diff --git a/docs/fundamentals/runtime-libraries/system-iasyncdisposable.md b/docs/fundamentals/runtime-libraries/system-iasyncdisposable.md deleted file mode 100644 index afe1a7ee99165..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-iasyncdisposable.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: System.IAsyncDisposable interface -description: Learn about the System.IAsyncDisposable interface. -ms.date: 12/31/2023 ---- -# System.IAsyncDisposable interface - -[!INCLUDE [context](includes/context.md)] - -In .NET, classes that own unmanaged resources usually implement the interface to provide a mechanism for releasing unmanaged resources synchronously. However, in some cases they need to provide an asynchronous mechanism for releasing unmanaged resources in addition to (or instead of) the synchronous one. Providing such a mechanism enables the consumer to perform resource-intensive dispose operations without blocking the main thread of a GUI application for a long time. - -The method of this interface returns a that represents the asynchronous dispose operation. Classes that own unmanaged resources implement this method, and the consumer of these classes calls this method on an object when it is no longer needed. - -The async methods are used in conjunction with the `async` and `await` keywords in C# and Visual Basic. For more information, see [The Task asynchronous programming model in C#](/dotnet/csharp/programming-guide/concepts/async/index) or [Asynchronous Programming with Async and Await (Visual Basic)](../../visual-basic/programming-guide/concepts/async/index.md). - -## Use an object that implements IAsyncDisposable - -If your application uses an object that implements `IAsyncDisposable`, you should call the object's implementation when you are finished using it. To make sure resources are released even in case of an exception, put the code that uses the `IAsyncDisposable` object into the [using](../../csharp/language-reference/keywords/using.md) statement (in C# beginning from version 8.0) or call the method inside a `finally` clause of the `try`/`finally` statement. For more information about the `try`/`finally` pattern, see [try-finally](/dotnet/csharp/language-reference/keywords/try-finally) (C#) or [Try...Catch...Finally Statement](../../visual-basic/language-reference/statements/try-catch-finally-statement.md) (Visual Basic). - -## Implement IAsyncDisposable - -You might implement `IAsyncDisposable` in the following situations: - -- When developing an asynchronous enumerator that owns unmanaged resources. Asynchronous enumerators are used with the C# 8.0 async streams feature. For more information about async streams, see [Tutorial: Generate and consume async streams using C# 8.0 and .NET Core 3.0](/dotnet/csharp/tutorials/generate-consume-asynchronous-stream). -- When your class owns unmanaged resources and releasing them requires a resource-intensive I/O operation, such as flushing the contents of an intermediate buffer into a file or sending a packet over a network to close a connection. - -Use the method to perform whatever cleanup is necessary after using the unmanaged resources, such as freeing, releasing, or resetting the unmanaged resources. For more information, see [Implement a DisposeAsync method](../../standard/garbage-collection/implementing-disposeasync.md). diff --git a/docs/fundamentals/runtime-libraries/system-idisposable.md b/docs/fundamentals/runtime-libraries/system-idisposable.md deleted file mode 100644 index 16baa7d24877e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-idisposable.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: System.IDisposable interface -description: Learn about the System.IDisposable interface. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.IDisposable interface - -[!INCLUDE [context](includes/context.md)] - -The primary use of the interface is to release unmanaged resources. The garbage collector automatically releases the memory allocated to a managed object when that object is no longer used. However, it's not possible to predict when garbage collection will occur. Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams. - -Use the method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. The consumer of an object can call this method when the object is no longer needed. - -> [!WARNING] -> It is a breaking change to add the interface to an existing class. Because pre-existing consumers of your type cannot call , you cannot be certain that unmanaged resources held by your type will be released. - -Because the implementation is called by the consumer of a type when the resources owned by an instance are no longer needed, you should either wrap the managed object in a (the recommended alternative), or you should override to free unmanaged resources in the event that the consumer forgets to call . - -> [!IMPORTANT] -> In .NET Framework, the C++ compiler supports deterministic disposal of resources and does not allow direct implementation of the method. - -For a detailed discussion about how this interface and the method are used, see the [Garbage Collection](../../standard/garbage-collection/index.md) and [Implementing a Dispose Method](../../standard/garbage-collection/implementing-dispose.md) topics. - -## Use an object that implements IDisposable - -If your app simply uses an object that implements the interface, you should call the object's implementation when you are finished using it. Depending on your programming language, you can do this in one of two ways: - -- By using a language construct such as the `using` statement in C# and Visual Basic, and the `use` statement or `using` function in F#. -- By wrapping the call to the implementation in a `try`/`finally` block. - -> [!NOTE] -> Documentation for types that implement note that fact and include a reminder to call its implementation. - -### The C#, F#, and Visual Basic Using statement - -If your language supports a construct such as the [using](../../csharp/language-reference/keywords/using.md) statement in C#, the [Using](../../visual-basic/language-reference/statements/using-statement.md) statement in Visual Basic, or the [use](../../fsharp/language-reference/resource-management-the-use-keyword.md) statement in F#, you can use it instead of explicitly calling yourself. The following example uses this approach in defining a `WordCount` class that preserves information about a file and the number of words in it. - -:::code language="csharp" source="./snippets/System/IDisposable/Overview/csharp/calling1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/IDisposable/Overview/fsharp/calling1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/IDisposable/Overview/vb/calling1.vb" id="Snippet1"::: - -The `using` statement (`use` expression in F#) is actually a syntactic convenience. At compile time, the language compiler implements the intermediate language (IL) for a `try`/`finally` block. - -For more information about the `using` statement, see the [Using Statement](../../visual-basic/language-reference/statements/using-statement.md) or [using Statement](/dotnet/csharp/language-reference/keywords/using-statement) topics. - -### The Try/Finally block - -If your programming language does not support a construct like the `using` statement in C# or Visual Basic, or the `use` statement in F#, or if you prefer not to use it, you can call the implementation from the `finally` block of a `try`/`finally` statement. The following example replaces the `using` block in the previous example with a `try`/`finally` block. - -:::code language="csharp" source="./snippets/System/IDisposable/Overview/csharp/calling2.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/IDisposable/Overview/fsharp/calling2.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/IDisposable/Overview/vb/calling2.vb" id="Snippet2"::: - -For more information about the `try`/`finally` pattern, see [Try...Catch...Finally Statement](../../visual-basic/language-reference/statements/try-catch-finally-statement.md), [try-finally](/dotnet/csharp/language-reference/keywords/try-finally), [try...finally Expression](../../fsharp/language-reference/exception-handling/the-try-finally-expression.md), or [try-finally Statement](/cpp/c-language/try-finally-statement-c). - -## Implement IDisposable - -You should implement if your type uses unmanaged resources directly or if you wish to use disposable resources yourself. The consumers of your type can call your implementation to free resources when the instance is no longer needed. To handle cases in which they fail to call , you should either use a class derived from to wrap the unmanaged resources, or you should override the method for a reference type. In either case, you use the method to perform whatever cleanup is necessary after using the unmanaged resources, such as freeing, releasing, or resetting the unmanaged resources. For more information about implementing , see [the Dispose(bool) method overload](../../standard/garbage-collection/implementing-dispose.md#the-disposebool-method-overload). - -> [!IMPORTANT] -> If you are defining a base class that uses unmanaged resources and that either has, or is likely to have, subclasses that should be disposed, you should implement the method and provide a second overload of `Dispose`, as discussed in the next section. - -## IDisposable and the inheritance hierarchy - -A base class with subclasses that should be disposable must implement as follows. You should use this pattern whenever you implement on any type that isn't `sealed` (`NotInheritable` in Visual Basic). - -- It should provide one public, non-virtual method and a protected virtual `Dispose(Boolean disposing)` method. -- The method must call `Dispose(true)` and should suppress finalization for performance. -- The base type should not include any finalizers. - -The following code fragment reflects the dispose pattern for base classes. It assumes that your type does not override the method. - -:::code language="csharp" source="./snippets/System/IDisposable/Overview/csharp/base1.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/IDisposable/Overview/fsharp/base1.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/IDisposable/Overview/vb/base1.vb" id="Snippet3"::: - -If you do override the method, your class should implement the following pattern. - -:::code language="csharp" source="./snippets/System/IDisposable/Overview/csharp/base2.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/IDisposable/Overview/fsharp/base2.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/IDisposable/Overview/vb/base2.vb" id="Snippet5"::: - -Subclasses should implement the disposable pattern as follows: - -- They must override `Dispose(Boolean)` and call the base class `Dispose(Boolean)` implementation. -- They can provide a finalizer if needed. The finalizer must call `Dispose(false)`. - -Note that derived classes do not themselves implement the interface and do not include a parameterless method. They only override the base class `Dispose(Boolean)` method. - -The following code fragment reflects the dispose pattern for derived classes. It assumes that your type does not override the method. - -:::code language="csharp" source="./snippets/System/IDisposable/Overview/csharp/derived1.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/IDisposable/Overview/fsharp/derived1.fs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/IDisposable/Overview/vb/derived1.vb" id="Snippet4"::: diff --git a/docs/fundamentals/runtime-libraries/system-int32.md b/docs/fundamentals/runtime-libraries/system-int32.md deleted file mode 100644 index b42dcb17c7562..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-int32.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: System.Int32 struct -description: Learn about the System.Int32 struct. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Int32 struct - -[!INCLUDE [context](includes/context.md)] - - is an immutable value type that represents signed integers with values that range from negative 2,147,483,648 (which is represented by the constant) through positive 2,147,483,647 (which is represented by the constant). .NET also includes an unsigned 32-bit integer value type, , which represents values that range from 0 to 4,294,967,295. - -## Instantiate an Int32 value - -You can instantiate an value in several ways: - -- You can declare an variable and assign it a literal integer value that is within the range of the data type. The following example declares two variables and assigns them values in this way. - - :::code language="csharp" source="./snippets/System/Int32/Overview/csharp/Instantiate1.cs" id="Snippet1"::: - :::code language="fsharp" source="./snippets/System/Int32/Overview/fsharp/Instantiate1.fs" id="Snippet1"::: - :::code language="vb" source="./snippets/System/Int32/Overview/vb/Instantiate1.vb" id="Snippet1"::: - -- You can assign the value of an integer type whose range is a subset of the type. This is a widening conversion that does not require a cast operator in C# or a conversion method in Visual Basic but does require one in F#. - - :::code language="csharp" source="./snippets/System/Int32/Overview/csharp/Instantiate1.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System/Int32/Overview/fsharp/Instantiate1.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System/Int32/Overview/vb/Instantiate1.vb" id="Snippet4"::: - -- You can assign the value of a numeric type whose range exceeds that of the type. This is a narrowing conversion, so it requires a cast operator in C# or F#, and a conversion method in Visual Basic if `Option Strict` is on. If the numeric value is a , , or value that includes a fractional component, the handling of its fractional part depends on the compiler performing the conversion. The following example performs narrowing conversions to assign several numeric values to variables. - - :::code language="csharp" source="./snippets/System/Int32/Overview/csharp/Instantiate1.cs" id="Snippet2"::: - :::code language="fsharp" source="./snippets/System/Int32/Overview/fsharp/Instantiate1.fs" id="Snippet2"::: - :::code language="vb" source="./snippets/System/Int32/Overview/vb/Instantiate1.vb" id="Snippet2"::: - -- You can call a method of the class to convert any supported type to an value. This is possible because supports the interface. The following example illustrates the conversion of an array of values to values. - - :::code language="csharp" source="./snippets/System/Convert/ToInt32/csharp/toint32_1.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System/Int32/Overview/fsharp/toint32_1.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System/Convert/Overview/vb/toint32_1.vb" id="Snippet4"::: - -- You can call the or method to convert the string representation of an value to an . The string can contain either decimal or hexadecimal digits. The following example illustrates the parse operation by using both a decimal and a hexadecimal string. - - :::code language="csharp" source="./snippets/System/Int32/Overview/csharp/Instantiate1.cs" id="Snippet3"::: - :::code language="fsharp" source="./snippets/System/Int32/Overview/fsharp/Instantiate1.fs" id="Snippet3"::: - :::code language="vb" source="./snippets/System/Int32/Overview/vb/Instantiate1.vb" id="Snippet3"::: - -## Perform operations on Int32 values - -The type supports standard mathematical operations such as addition, subtraction, division, multiplication, negation, and unary negation. Like the other integral types, the type also supports the bitwise `AND`, `OR`, `XOR`, left shift, and right shift operators. - -You can use the standard numeric operators to compare two values, or you can call the or method. - -You can also call the members of the class to perform a wide range of numeric operations, including getting the absolute value of a number, calculating the quotient and remainder from integral division, determining the maximum or minimum value of two integers, getting the sign of a number, and rounding a number. - -## Represent an Int32 as a string - -The type provides full support for standard and custom numeric format strings. (For more information, see [Formatting Types](../../standard/base-types/formatting-types.md), [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md), and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md).) - -To format an value as an integral string with no leading zeros, you can call the parameterless method. By using the "D" format specifier, you can also include a specified number of leading zeros in the string representation. By using the "N" format specifier, you can include group separators and specify the number of decimal digits to appear in the string representation of the number. By using the "X" format specifier, you can represent an value as a hexadecimal string. The following example formats the elements in an array of values in these four ways. - -:::code language="csharp" source="./snippets/System/Int32/Overview/csharp/Formatting1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Int32/Overview/fsharp/Formatting1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Int32/Overview/vb/Formatting1.vb" id="Snippet1"::: - -You can also format an value as a binary, octal, decimal, or hexadecimal string by calling the method and supplying the base as the method's second parameter. The following example calls this method to display the binary, octal, and hexadecimal representations of an array of integer values. - -:::code language="csharp" source="./snippets/System/Int32/Overview/csharp/Formatting1.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Int32/Overview/fsharp/Formatting1.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Int32/Overview/vb/Formatting1.vb" id="Snippet2"::: - -## Work with non-decimal 32-bit integer values - -In addition to working with individual integers as decimal values, you may want to perform bitwise operations with integer values, or work with the binary or hexadecimal representations of integer values. values are represented in 31 bits, with the thirty-second bit used as a sign bit. Positive values are represented by using sign-and-magnitude representation. Negative values are in two's complement representation. This is important to keep in mind when you perform bitwise operations on values or when you work with individual bits. In order to perform a numeric, Boolean, or comparison operation on any two non-decimal values, both values must use the same representation. diff --git a/docs/fundamentals/runtime-libraries/system-int64.md b/docs/fundamentals/runtime-libraries/system-int64.md deleted file mode 100644 index 04df783a373bc..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-int64.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: System.Int64 struct -description: Learn about the System.Int64 struct. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Int64 struct - -[!INCLUDE [context](includes/context.md)] - - is an immutable value type that represents signed integers with values that range from negative 9,223,372,036,854,775,808 (which is represented by the constant) through positive 9,223,372,036,854,775,807 (which is represented by the constant). .NET also includes an unsigned 64-bit integer value type, , which represents values that range from 0 to 18,446,744,073,709,551,615. - -## Instantiate an Int64 value - -You can instantiate an value in several ways: - -- You can declare an variable and assign it a literal integer value that is within the range of the data type. The following example declares two variables and assigns them values in this way. - - :::code language="csharp" source="./snippets/System/Int64/Overview/csharp/instantiate1.cs" id="Snippet1"::: - :::code language="fsharp" source="./snippets/System/Int64/Overview/fsharp/instantiate1.fs" id="Snippet1"::: - :::code language="vb" source="./snippets/System/Int64/Overview/vb/instantiate1.vb" id="Snippet1"::: - -- You can assign the value of an integral type whose range is a subset of the type. This is a widening conversion that does not require a cast operator in C# or a conversion method in Visual Basic. In F#, only the type can be widened automatically. - - :::code language="csharp" source="./snippets/System/Int64/Overview/csharp/instantiate1.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System/Int64/Overview/fsharp/instantiate1.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System/Int64/Overview/vb/instantiate1.vb" id="Snippet4"::: - -- You can assign the value of a numeric type whose range exceeds that of the type. This is a narrowing conversion, so it requires a cast operator in C# or F# and a conversion method in Visual Basic if `Option Strict` is on. If the numeric value is a , , or value that includes a fractional component, the handling of its fractional part depends on the compiler performing the conversion. The following example performs narrowing conversions to assign several numeric values to variables. - - :::code language="csharp" source="./snippets/System/Int64/Overview/csharp/instantiate1.cs" id="Snippet2"::: - :::code language="fsharp" source="./snippets/System/Int64/Overview/fsharp/instantiate1.fs" id="Snippet2"::: - :::code language="vb" source="./snippets/System/Int64/Overview/vb/instantiate1.vb" id="Snippet2"::: - -- You can call a method of the class to convert any supported type to an value. This is possible because supports the interface. The following example illustrates the conversion of an array of values to values. - - :::code language="csharp" source="./snippets/System/Convert/ToInt64/csharp/toint64_1.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System/Convert/ToInt64/fsharp/toint64_1.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System/Convert/Overview/vb/toint64_1.vb" id="Snippet4"::: - -- You can call the or method to convert the string representation of an value to an . The string can contain either decimal or hexadecimal digits. The following example illustrates the parse operation by using both a decimal and a hexadecimal string. - - :::code language="csharp" source="./snippets/System/Int64/Overview/csharp/instantiate1.cs" id="Snippet3"::: - :::code language="fsharp" source="./snippets/System/Int64/Overview/fsharp/instantiate1.fs" id="Snippet3"::: - :::code language="vb" source="./snippets/System/Int64/Overview/vb/instantiate1.vb" id="Snippet3"::: - -## Perform operations on Int64 values - -The type supports standard mathematical operations such as addition, subtraction, division, multiplication, negation, and unary negation. Like the other integral types, the type also supports the bitwise `AND`, `OR`, `XOR`, left shift, and right shift operators. - -You can use the standard numeric operators to compare two values, or you can call the or method. - -You can also call the members of the class to perform a wide range of numeric operations, including getting the absolute value of a number, calculating the quotient and remainder from integral division, determining the maximum or minimum value of two long integers, getting the sign of a number, and rounding a number. - -## Represent an Int64 as a string - -The type provides full support for standard and custom numeric format strings. (For more information, see [Formatting Types](../../standard/base-types/formatting-types.md), [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md), and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md).) - -To format an value as an integral string with no leading zeros, you can call the parameterless method. By using the "D" format specifier, you can also include a specified number of leading zeros in the string representation. By using the "N" format specifier, you can include group separators and specify the number of decimal digits to appear in the string representation of the number. By using the "X" format specifier, you can represent an value as a hexadecimal string. The following example formats the elements in an array of values in these four ways. - -:::code language="csharp" source="./snippets/System/Int64/Overview/csharp/formatting1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Convert/ToInt64/fsharp/formatting1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Int64/Overview/vb/formatting1.vb" id="Snippet1"::: - -You can also format an value as a binary, octal, decimal, or hexadecimal string by calling the method and supplying the base as the method's second parameter. The following example calls this method to display the binary, octal, and hexadecimal representations of an array of integer values. - -:::code language="csharp" source="./snippets/System/Int64/Overview/csharp/formatting1.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Convert/ToInt64/fsharp/formatting1.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Int64/Overview/vb/formatting1.vb" id="Snippet2"::: - -## Work with non-decimal 64-bit integer values - -In addition to working with individual long integers as decimal values, you might want to perform bitwise operations or work with the binary or hexadecimal representations of long integer values. values are represented in 63 bits, with the sixty-fourth bit used as a sign bit. Positive values are represented by using sign-and-magnitude representation. Negative values are in two's complement representation. This is important to keep in mind when you perform bitwise operations on values or when you work with individual bits. To perform a numeric, Boolean, or comparison operation on any two non-decimal values, both values must use the same representation. diff --git a/docs/fundamentals/runtime-libraries/system-invalidcastexception.md b/docs/fundamentals/runtime-libraries/system-invalidcastexception.md deleted file mode 100644 index 7f301fedfb00b..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-invalidcastexception.md +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: System.InvalidCastException class -description: Learn about the System.InvalidCastException class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB - - FSharp ---- -# System.InvalidCastException class - -[!INCLUDE [context](includes/context.md)] - -.NET supports automatic conversion from derived types to their base types and back to the derived type, as well as from types that present interfaces to interface objects and back. It also includes a variety of mechanisms that support custom conversions. For more information, see [Type Conversion in .NET](../../standard/base-types/type-conversion.md). - -An exception is thrown when the conversion of an instance of one type to another type is not supported. For example, attempting to convert a value to a value throws an exception. It differs from an exception, which is thrown when a conversion of one type to another is supported, but the value of the source type is outside the range of the target type. An exception is caused by developer error and should not be handled in a `try/catch` block. Instead, the cause of the exception should be eliminated. - -For information about conversions supported by the system, see the class. For errors that occur when the destination type can store source type values but is not large enough to store a specific source value, see the exception. - -> [!NOTE] -> In many cases, your language compiler detects that no conversion exists between the source type and the target type and issues a compiler error. - -Some of the conditions under which an attempted conversion throws an exception are discussed in the following sections. - -For an explicit reference conversion to be successful, the source value must be `null`, or the object type referenced by the source argument must be convertible to the destination type by an implicit reference conversion. - -The following intermediate language (IL) instructions throw an exception: - -- `castclass` -- `refanyval` -- `unbox` - - uses the HRESULT `COR_E_INVALIDCAST`, which has the value 0x80004002. - -For a list of initial property values for an instance of , see the constructors. - -## Primitive types and IConvertible - -You directly or indirectly call a primitive type's implementation that does not support a particular conversion. For example, trying to convert a value to a or a value to an throws an exception. The following example calls both the and methods to convert a value to a . In both cases, the method call throws an exception. - -:::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/iconvertible1.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/iconvertible1.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/InvalidCastException/Overview/vb/iconvertible1.vb" id="Snippet2"::: - -Because the conversion is not supported, there is no workaround. - -## The Convert.ChangeType method - -You've called the method to convert an object from one type to another, but one or both types don't implement the interface. - -In most cases, because the conversion is not supported, there is no workaround. In some cases, a possible workaround is to manually assign property values from the source type to similar properties of a the target type. - -## Narrowing conversions and IConvertible implementations - -Narrowing operators define the explicit conversions supported by a type. A casting operator in C# or the `CType` conversion method in Visual Basic (if `Option Strict` is on) is required to perform the conversion. - -However, if neither the source type nor the target type defines an explicit or narrowing conversion between the two types, and the implementation of one or both types doesn't support a conversion from the source type to the target type, an exception is thrown. - -In most cases, because the conversion is not supported, there is no workaround. - -## Downcasting - -You're downcasting, that is, trying to convert an instance of a base type to one of its derived types. In the following example, trying to convert a `Person` object to a `PersonWithID` object fails. - -:::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/basetoderived1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/basetoderived1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/InvalidCastException/Overview/vb/basetoderived1.vb" id="Snippet1"::: - -As the example shows, the downcast succeeds only if the `Person` object was created by an upcast from a `PersonWithId` object to a `Person` object, or if the `Person` object is `null`. - -## Conversion from an interface object - -You're attempting to convert an interface object to a type that implements that interface, but the target type is not the same type or a base class of the type from which the interface object was originally derived. The following example throws an exception when it attempts to convert an object to a object. The conversion fails because although the class implements the interface, the object is not related to the class from which the interface object was derived. - -:::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/Interface1.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/Interface1.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/InvalidCastException/Overview/vb/Interface1.vb" id="Snippet3"::: - -As the exception message indicates, the conversion would succeed only if the interface object is converted back to an instance of the original type, in this case a . The conversion would also succeed if the interface object is converted to an instance of a base type of the original type. - -## String conversions - -You're trying to convert a value or an object to its string representation by using a casting operator in C#. In the following example, both the attempt to cast a value to a string and the attempt to cast an integer to a string throw an exception. - -:::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/ToString1.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/ToString1.fs" id="Snippet4"::: - -> [!NOTE] -> Using the Visual Basic `CStr` operator to convert a value of a primitive type to a string succeeds. The operation does not throw an exception. - -To successfully convert an instance of any type to its string representation, call its `ToString` method, as the following example does. The `ToString` method is always present, since the method is defined by the class and therefore is either inherited or overridden by all managed types. - -:::code language="csharp" source="./snippets/System/InvalidCastException/Overview/csharp/ToString2.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/InvalidCastException/Overview/fsharp/ToString2.fs" id="Snippet5"::: - -## Visual Basic 6.0 migration - -You're upgrading a Visual Basic 6.0 application with a call to a custom event in a user control to Visual Basic .NET, and an exception is thrown with the message, "Specified cast is not valid." To eliminate this exception, change the line of code in your form (such as `Form1`) - -```vb -Call UserControl11_MyCustomEvent(UserControl11, New UserControl1.MyCustomEventEventArgs(5)) -``` - -and replace it with the following line of code: - -```vb -Call UserControl11_MyCustomEvent(UserControl11(0), New UserControl1.MyCustomEventEventArgs(5)) -``` diff --git a/docs/fundamentals/runtime-libraries/system-invalidoperationexception.md b/docs/fundamentals/runtime-libraries/system-invalidoperationexception.md deleted file mode 100644 index 1bf217c09d2f3..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-invalidoperationexception.md +++ /dev/null @@ -1,256 +0,0 @@ ---- -title: System.InvalidOperationException class -description: Learn about the System.InvalidOperationException class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB - - FSharp ---- -# System.InvalidOperationException class - -[!INCLUDE [context](includes/context.md)] - - is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments. Typically, it's thrown when the state of an object cannot support the method call. For example, an exception is thrown by methods such as: - -- if objects of a collection are modified after the enumerator is created. For more information, see [Changing a collection while iterating it](#changing-a-collection-while-iterating-it). -- if the resource set is closed before the method call is made. -- , if the object or objects to be added would result in an incorrectly structured XML document. -- A method that attempts to manipulate the UI from a thread that is not the main or UI thread. - -> [!IMPORTANT] -> Because the exception can be thrown in a wide variety of circumstances, it is important to read the exception message returned by the property. - - uses the HRESULT `COR_E_INVALIDOPERATION`, which has the value 0x80131509. - -For a list of initial property values for an instance of , see the constructors. - -## Common causes of InvalidOperationException exceptions - -The following sections show how some common cases in which in exception is thrown in an app. How you handle the issue depends on the specific situation. Most commonly, however, the exception results from developer error, and the exception can be anticipated and avoided. - -### Updating a UI thread from a non-UI thread - -Often, worker threads are used to perform some background work that involves gathering data to be displayed in an application's user interface. However. most GUI (graphical user interface) application frameworks for .NET, such as Windows Forms and Windows Presentation Foundation (WPF), let you access GUI objects only from the thread that creates and manages the UI (the Main or UI thread). An is thrown when you try to access a UI element from a thread other than the UI thread. The text of the exception message is shown in the following table. - -|Application Type|Message| -|----------------------|-------------| -|WPF app|**The calling thread cannot access this object because a different thread owns it.**| -|UWP app|**The application called an interface that was marshaled for a different thread.**| -|Windows Forms app|**Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on.**| - -UI frameworks for .NET implement a *dispatcher* pattern that includes a method to check whether a call to a member of a UI element is being executed on the UI thread, and other methods to schedule the call on the UI thread: - -- In WPF apps, call the method to determine if a method is running on a non-UI thread. It returns `true` if the method is running on the UI thread and `false` otherwise. Call one of the overloads of the method to schedule the call on the UI thread. -- In UWP apps, check the property to determine if a method is running on a non-UI thread. Call the method to execute a delegate that updates the UI thread. -- In Windows Forms apps, use the property to determine if a method is running on a non-UI thread. Call one of the overloads of the method to execute a delegate that updates the UI thread. - -The following examples illustrate the exception that is thrown when you attempt to update a UI element from a thread other than the thread that created it. Each example requires that you create two controls: - -- A text box control named `textBox1`. In a Windows Forms app, you should set its property to `true`. -- A button control named `threadExampleBtn`. The example provides a handler, `ThreadsExampleBtn_Click`, for the button's `Click` event. - -In each case, the `threadExampleBtn_Click` event handler calls the `DoSomeWork` method twice. The first call runs synchronously and succeeds. But the second call, because it runs asynchronously on a thread pool thread, attempts to update the UI from a non-UI thread. This results in a exception. - -#### WPF apps - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/WPF1/MainWindow.xaml.cs" id="Snippet1"::: - -The following version of the `DoSomeWork` method eliminates the exception in a WPF app. - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/WPF2/MainWindowDispatcher.xaml.cs" id="Snippet3"::: - -#### Windows Forms apps - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/WinForms/Form1.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/WinForms/Form1.vb" id="Snippet2"::: - -The following version of the `DoSomeWork` method eliminates the exception in a Windows Forms app. - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/WinForms/Form11.cs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/WinForms/Form11.vb" id="Snippet5"::: - -### Changing a collection while iterating it - -The `foreach` statement in C#, `for...in` in F#, or `For Each` statement in Visual Basic is used to iterate the members of a collection and to read or modify its individual elements. However, it can't be used to add or remove items from the collection. Doing this throws an exception with a message that is similar to, "**Collection was modified; enumeration operation may not execute.**" - -The following example iterates a collection of integers attempts to add the square of each integer to the collection. The example throws an with the first call to the method. - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Iterating1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Iterating1.vb" id="Snippet1"::: - -You can eliminate the exception in one of two ways, depending on your application logic: - -- If elements must be added to the collection while iterating it, you can iterate it by index using the `for` (`for..to` in F#) statement instead of `foreach`, `for...in`, or `For Each`. The following example uses the for statement to add the square of numbers in the collection to the collection. - - :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating2.cs" id="Snippet2"::: - :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Iterating2.fs" id="Snippet2"::: - :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Iterating2.vb" id="Snippet2"::: - - Note that you must establish the number of iterations before iterating the collection either by using a counter inside the loop that will exit the loop appropriately, by iterating backward, from `Count` - 1 to 0, or, as the example does, by assigning the number of elements in the array to a variable and using it to establish the upper bound of the loop. Otherwise, if an element is added to the collection on every iteration, an endless loop results. - -- If it is not necessary to add elements to the collection while iterating it, you can store the elements to be added in a temporary collection that you add when iterating the collection has finished. The following example uses this approach to add the square of numbers in a collection to a temporary collection, and then to combine the collections into a single array object. - - :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Iterating3.cs" id="Snippet3"::: - :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Iterating3.fs" id="Snippet3"::: - :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Iterating3.vb" id="Snippet3"::: - -### Sorting an array or collection whose objects cannot be compared - -General-purpose sorting methods, such as the method or the method, usually require that at least one of the objects to be sorted implement the or the interface. If not, the collection or array cannot be sorted, and the method throws an exception. The following example defines a `Person` class, stores two `Person` objects in a generic object, and attempts to sort them. As the output from the example shows, the call to the method throws an . - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort1.cs" id="Snippet12"::: -:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort1.fs" id="Snippet12"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/List_Sort1.vb" id="Snippet12"::: - -You can eliminate the exception in any of three ways: - -- If you can own the type that you are trying to sort (that is, if you control its source code), you can modify it to implement the or the interface. This requires that you implement either the or the method. Adding an interface implementation to an existing type is not a breaking change. - - The following example uses this approach to provide an implementation for the `Person` class. You can still call the collection or array's general sorting method and, as the output from the example shows, the collection sorts successfully. - - :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort2.cs" id="Snippet13"::: - :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort2.fs" id="Snippet13"::: - :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/List_Sort2.vb" id="Snippet13"::: - -- If you cannot modify the source code for the type you are trying to sort, you can define a special-purpose sorting class that implements the interface. You can call an overload of the `Sort` method that includes an parameter. This approach is especially useful if you want to develop a specialized sorting class that can sort objects based on multiple criteria. - - The following example uses the approach by developing a custom `PersonComparer` class that is used to sort `Person` collections. It then passes an instance of this class to the method. - - :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort3.cs" id="Snippet14"::: - :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort3.fs" id="Snippet14"::: - :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/List_Sort3.vb" id="Snippet14"::: - -- If you cannot modify the source code for the type you are trying to sort, you can create a delegate to perform the sorting. The delegate signature is - - ```vb - Function Comparison(Of T)(x As T, y As T) As Integer - ``` - - ```csharp - int Comparison(T x, T y) - ``` - - The following example uses the approach by defining a `PersonComparison` method that matches the delegate signature. It then passes this delegate to the method. - - :::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/List_Sort4.cs" id="Snippet15"::: - :::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/List_Sort4.fs" id="Snippet15"::: - :::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/List_Sort4.vb" id="Snippet15"::: - -### Casting a Nullable\ that's null to its underlying type - -Attempting to cast a value that is `null` to its underlying type throws an exception and displays the error message, "**Nullable object must have a value.** - -The following example throws an exception when it attempts to iterate an array that includes a `Nullable(Of Integer)` value. - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Nullable1.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Nullable1.fs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Nullable1.vb" id="Snippet4"::: - -To prevent the exception: - -- Use the property to select only those elements that are not `null`. -- Call one of the overloads to provide a default value for a `null` value. - -The following example does both to avoid the exception. - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Nullable2.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Nullable2.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Nullable2.vb" id="Snippet5"::: - -### Call a System.Linq.Enumerable method on an empty collection - -The , , , , , , , and methods perform operations on a sequence and return a single result. Some overloads of these methods throw an exception when the sequence is empty, while other overloads return `null`. The method also throws an exception when the sequence contains more than one element. - -> [!NOTE] -> Most of the methods that throw an exception are overloads. Be sure that you understand the behavior of the overload that you choose. - -The following table lists the exception messages from the exception objects thrown by calls to some methods. - -|Method|Message| -|------------|-------------| -|`Aggregate`
`Average`
`Last`
`Max`
`Min`|**Sequence contains no elements**| -|`First`|**Sequence contains no matching element**| -|`Single`
`SingleOrDefault`|**Sequence contains more than one matching element**| - -How you eliminate or handle the exception depends on your application's assumptions and on the particular method you call. - -- When you deliberately call one of these methods without checking for an empty sequence, you are assuming that the sequence is not empty, and that an empty sequence is an unexpected occurrence. In this case, catching or rethrowing the exception is appropriate. - -- If your failure to check for an empty sequence was inadvertent, you can call one of the overloads of the overload to determine whether a sequence contains any elements. - - > [!TIP] - > Calling the method before generating a sequence can improve performance if the data to be processed might contain a large number of elements or if operation that generates the sequence is expensive. - -- If you've called a method such as , , or , you can substitute an alternate method, such as , , or , that returns a default value instead of a member of the sequence. - -The examples provide additional detail. - -The following example uses the method to compute the average of a sequence whose values are greater than 4. Since no values from the original array exceed 4, no values are included in the sequence, and the method throws an exception. - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable1.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable1.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Enumerable1.vb" id="Snippet6"::: - -The exception can be eliminated by calling the method to determine whether the sequence contains any elements before calling the method that processes the sequence, as the following example shows. - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable2.cs" id="Snippet7"::: -:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable2.fs" id="Snippet7"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Enumerable2.vb" id="Snippet7"::: - -The method returns the first item in a sequence or the first element in a sequence that satisfies a specified condition. If the sequence is empty and therefore does not have a first element, it throws an exception. - -In the following example, the method throws an exception because the dbQueryResults array doesn't contain an element greater than 4. - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable3.cs" id="Snippet8"::: -:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable3.fs" id="Snippet8"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Enumerable3.vb" id="Snippet8"::: - -You can call the method instead of to return a specified or default value. If the method does not find a first element in the sequence, it returns the default value for that data type. The default value is `null` for a reference type, zero for a numeric data type, and for the type. - -> [!NOTE] -> Interpreting the value returned by the method is often complicated by the fact that the default value of the type can be a valid value in the sequence. In this case, you an call the method to determine whether the sequence has valid members before calling the method. - -The following example calls the method to prevent the exception thrown in the previous example. - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable4.cs" id="Snippet9"::: -:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable4.fs" id="Snippet9"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Enumerable4.vb" id="Snippet9"::: - -### Call Enumerable.Single or Enumerable.SingleOrDefault on a sequence without one element - -The method returns the only element of a sequence, or the only element of a sequence that meets a specified condition. If there are no elements in the sequence, or if there is more than one element , the method throws an exception. - -You can use the method to return a default value instead of throwing an exception when the sequence contains no elements. However, the method still throws an exception when the sequence contains more than one element. - -The following table lists the exception messages from the exception objects thrown by calls to the and methods. - -| Method | Message | -|-----------------------------------|------------------------------------------------------| -| `Single` | **Sequence contains no matching element** | -| `Single`
`SingleOrDefault` | **Sequence contains more than one matching element** | - -In the following example, the call to the method throws an exception because the sequence doesn't have an element greater than 4. - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable5.cs" id="Snippet10"::: -:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable5.fs" id="Snippet10"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Enumerable5.vb" id="Snippet10"::: - -The following example attempts to prevent the exception thrown when a sequence is empty by instead calling the method. However, because this sequence returns multiple elements whose value is greater than 2, it also throws an exception. - -:::code language="csharp" source="./snippets/System/InvalidOperationException/Overview/csharp/Other/Enumerable6.cs" id="Snippet11"::: -:::code language="fsharp" source="./snippets/System/InvalidOperationException/Overview/fsharp/Enumerable6.fs" id="Snippet11"::: -:::code language="vb" source="./snippets/System/InvalidOperationException/Overview/vb/Other/Enumerable6.vb" id="Snippet11"::: - -Calling the method assumes that either a sequence or the sequence that meets specified criteria contains only one element. assumes a sequence with zero or one result, but no more. If this assumption is a deliberate one on your part and these conditions are not met, rethrowing or catching the resulting is appropriate. Otherwise, or if you expect that invalid conditions will occur with some frequency, you should consider using some other method, such as or . - -### Dynamic cross-application domain field access - -The common intermediate language (CIL) instruction throws an exception if the object containing the field whose address you are trying to retrieve is not within the application domain in which your code is executing. The address of a field can only be accessed from the application domain in which it resides. - -## Throw an InvalidOperationException exception - -You should throw an exception only when the state of your object for some reason does not support a particular method call. That is, the method call is valid in some circumstances or contexts, but is invalid in others. - -If the method invocation failure is due to invalid arguments, then or one of its derived classes, or , should be thrown instead. diff --git a/docs/fundamentals/runtime-libraries/system-io-filestream.md b/docs/fundamentals/runtime-libraries/system-io-filestream.md deleted file mode 100644 index 54e05646265f2..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-io-filestream.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: System.IO.FileStream class -description: Learn about the System.IO.FileStream class. -ms.date: 12/31/2023 ---- -# System.IO.FileStream class - -[!INCLUDE [context](includes/context.md)] - -Use the class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output. You can use the , , , and methods to perform synchronous operations, or the , , , and methods to perform asynchronous operations. Use the asynchronous methods to perform resource-intensive file operations without blocking the main thread. This performance consideration is particularly important in a Windows 8.x Store app or desktop app where a time-consuming stream operation can block the UI thread and make your app appear as if it is not working. buffers input and output for better performance. - -> [!IMPORTANT] -> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. - -The property detects whether the file handle was opened asynchronously. You specify this value when you create an instance of the class using a constructor that has an `isAsync`, `useAsync`, or `options` parameter. When the property is `true`, the stream utilizes overlapped I/O to perform file operations asynchronously. However, the property does not have to be `true` to call the , , or method. When the property is `false` and you call the asynchronous read and write operations, the UI thread is still not blocked, but the actual I/O operation is performed synchronously. - -The method supports random access to files. allows the read/write position to be moved to any position within the file. This is done with byte offset reference point parameters. The byte offset is relative to the seek reference point, which can be the beginning, the current position, or the end of the underlying file, as represented by the three members of the enumeration. - -> [!NOTE] -> Disk files always support random access. At the time of construction, the property value is set to `true` or `false` depending on the underlying file type. If the underlying file type is FILE_TYPE_DISK, as defined in winbase.h, the property value is `true`. Otherwise, the property value is `false`. - -If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined. - -For directory operations and other file operations, see the , , and classes. The class is a utility class that has static methods primarily for the creation of objects based on file paths. The class creates a stream from a byte array and is similar to the class. - -For a list of common file and directory operations, see [Common I/O Tasks](../../standard/io/common-i-o-tasks.md). - -## Detection of stream position changes - -When a object does not have an exclusive hold on its handle, another thread could access the file handle concurrently and change the position of the operating system's file pointer that is associated with the file handle. In this case, the cached position in the object and the cached data in the buffer could be compromised. The object routinely performs checks on methods that access the cached buffer to ensure that the operating system's handle position is the same as the cached position used by the object. - -If an unexpected change in the handle position is detected in a call to the method, .NET discards the contents of the buffer and reads the stream from the file again. This can affect performance, depending on the size of the file and any other processes that could affect the position of the file stream. - -If an unexpected change in the handle position is detected in a call to the method, the contents of the buffer are discarded and an exception is thrown. - -A object will not have an exclusive hold on its handle when either the property is accessed to expose the handle or the object is given the property in its constructor. diff --git a/docs/fundamentals/runtime-libraries/system-io-filesystemwatcher.md b/docs/fundamentals/runtime-libraries/system-io-filesystemwatcher.md deleted file mode 100644 index 90c3154d05bdc..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-io-filesystemwatcher.md +++ /dev/null @@ -1,51 +0,0 @@ ---- -title: System.IO.FileSystemWatcher class -description: Learn about the System.IO.FileSystemWatcher class. -ms.date: 12/31/2023 ---- -# System.IO.FileSystemWatcher class - -[!INCLUDE [context](includes/context.md)] - -Use to watch for changes in a specified directory. You can watch for changes in files and subdirectories of the specified directory. You can create a component to watch files on a local computer, a network drive, or a remote computer. - -To watch for changes in all files, set the property to an empty string ("") or use wildcards ("*.\*"). To watch a specific file, set the property to the file name. For example, to watch for changes in the file MyDoc.txt, set the property to "MyDoc.txt". You can also watch for changes in a certain type of file. For example, to watch for changes in text files, set the property to "\*.txt". - -There are several types of changes you can watch for in a directory or file. For example, you can watch for changes in `Attributes`, the `LastWrite` date and time, or the `Size` of files or directories. This is done by setting the property to one of the values. For more information on the type of changes you can watch, see . - -You can watch for renaming, deletion, or creation of files or directories. For example, to watch for renaming of text files, set the property to "*.txt" and call the method with a specified for its parameter. - -The Windows operating system notifies your component of file changes in a buffer created by the . If there are many changes in a short time, the buffer can overflow. This causes the component to lose track of changes in the directory, and it will only provide blanket notification. Increasing the size of the buffer with the property is expensive, as it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small yet large enough to not miss any file change events. To avoid a buffer overflow, use the and properties so you can filter out unwanted change notifications. - -For a list of initial property values for an instance of , see the constructor. - -Considerations when using the class: - -- Hidden files are not ignored. -- In some systems, reports changes to files using the short 8.3 file name format. For example, a change to "LongFileName.LongExtension" could be reported as "LongFil~.Lon". -- This class contains a link demand and an inheritance demand at the class level that applies to all members. A is thrown when either the immediate caller or the derived class does not have full-trust permission. For details about security demands, see [Link Demands](/dotnet/framework/misc/link-demands). -- The maximum size you can set for the property for monitoring a directory over the network is 64 KB. - -## Copy and move folders - -The operating system and object interpret a cut-and-paste action or a move action as a rename action for a folder and its contents. If you cut and paste a folder with files into a folder being watched, the object reports only the folder as new, but not its contents because they are essentially only renamed. - -To be notified that the contents of folders have been moved or copied into a watched folder, provide and event handler methods as suggested in the following table. - -|Event Handler|Events Handled|Performs| -|-------------------|--------------------|--------------| -||, , |Report changes in file attributes, created files, and deleted files.| -|||List the old and new paths of renamed files and folders, expanding recursively if needed.| - -## Events and buffer sizes - -Note that several factors can affect which file system change events are raised, as described by the following: - -- Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several and some and events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by . -- The can watch disks as long as they are not switched or removed. The does not raise events for CDs and DVDs, because time stamps and properties cannot change. Remote computers must have one of the required platforms installed for the component to function properly. - -Note that a may miss an event when the buffer size is exceeded. To avoid missing events, follow these guidelines: - -- Increase the buffer size by setting the property. -- Avoid watching files with long file names, because a long file name contributes to filling up the buffer. Consider renaming these files using shorter names. -- Keep your event handling code as short as possible. diff --git a/docs/fundamentals/runtime-libraries/system-linq-expressions-binaryexpression.md b/docs/fundamentals/runtime-libraries/system-linq-expressions-binaryexpression.md deleted file mode 100644 index 355e1f593da07..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-linq-expressions-binaryexpression.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: System.Linq.Expressions.BinaryExpression class -description: Learn about the System.Linq.Expressions.BinaryExpression class. -ms.date: 12/31/2023 ---- -# System.Linq.Expressions.BinaryExpression class - -[!INCLUDE [context](includes/context.md)] - -The class represents an expression that has a binary operator. - -The following tables summarize the factory methods that can be used to create a that has a specific node type, represented by the property. Each table contains information for a specific class of operations such as arithmetic or bitwise. - -## Binary arithmetic operations - -|Node Type|Factory Method| -|---------------|--------------------| -||| -||| -||| -||| -||| -||| -||| -||| -||| - -## Bitwise operations - -|Node Type|Factory Method| -|---------------|--------------------| -||| -||| -||| - -## Shift operations - -|Node Type|Factory Method| -|---------------|--------------------| -||| -||| - -## Conditional Boolean operations - -|Node Type|Factory Method| -|---------------|--------------------| -||| -||| - -## Comparison operations - -|Node Type|Factory Method| -|---------------|--------------------| -||| -||| -||| -||| -||| -||| - -## Coalescing operations - -|Node Type|Factory Method| -|---------------|--------------------| -||| - -## Array indexing operations - -|Node Type|Factory Method| -|---------------|--------------------| -||| - -In addition, the methods can also be used to create a . These factory methods can be used to create a of any node type that represents a binary operation. The parameter of these methods that is of type specifies the desired node type. diff --git a/docs/fundamentals/runtime-libraries/system-linq-expressions-expression-add.md b/docs/fundamentals/runtime-libraries/system-linq-expressions-expression-add.md deleted file mode 100644 index bcaeffc639fcf..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-linq-expressions-expression-add.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: System.Linq.Expressions.Expression.Add methods -description: Learn about the System.Linq.Expressions.Expression.Add methods. -ms.date: 01/24/2024 ---- -# System.Linq.Expressions.Expression.Add methods - -[!INCLUDE [context](includes/context.md)] - -The method returns a that has the property set to the implementing method. The property is set to the type of the node. If the node is lifted, the and properties are both `true`. Otherwise, they are `false`. The property is `null`. - -The following information describes the implementing method, the node type, and whether a node is lifted. - -## Implementing method - -The following rules determine the selected implementing method for the operation: - -- If the property of either `left` or `right` represents a user-defined type that overloads the addition operator, the that represents that method is the implementing method. -- Otherwise, if `left`.Type and `right`.Type are numeric types, the implementing method is `null`. - -## Node type and lifted versus non-lifted - -If the implementing method is not `null`: - -- If `left`.Type and `right`.Type are assignable to the corresponding argument types of the implementing method, the node is not lifted. The type of the node is the return type of the implementing method. -- If the following two conditions are satisfied, the node is lifted and the type of the node is the nullable type that corresponds to the return type of the implementing method: - - - `left`.Type and `right`.Type are both value types of which at least one is nullable and the corresponding non-nullable types are equal to the corresponding argument types of the implementing method. - - The return type of the implementing method is a non-nullable value type. - -If the implementing method is `null`: - -- If `left`.Type and `right`.Type are both non-nullable, the node is not lifted. The type of the node is the result type of the predefined addition operator. -- If `left`.Type and `right`.Type are both nullable, the node is lifted. The type of the node is the nullable type that corresponds to the result type of the predefined addition operator. diff --git a/docs/fundamentals/runtime-libraries/system-midpointrounding.md b/docs/fundamentals/runtime-libraries/system-midpointrounding.md deleted file mode 100644 index 0abdea1f8a282..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-midpointrounding.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: System.MidpointRounding enum -description: Learn about the System.MidpointRounding enum. -ms.date: 12/31/2023 ---- -# System.MidpointRounding enum - -[!INCLUDE [context](includes/context.md)] - -Use the enumeration with appropriate overloads of , , and to provide more control of the rounding process. - -There are two overall rounding strategies—*round to nearest* and *directed rounding*—and each enumeration field participates in exactly one of these strategies. - -## Round to nearest - -Fields: - -- -- - -A round-to-nearest operation takes an original number with an implicit or specified precision; examines the next digit, which is at that precision plus one; and returns the nearest number with the same precision as the original number. For positive numbers, if the next digit is from 0 through 4, the nearest number is toward negative infinity. If the next digit is from 6 through 9, the nearest number is toward positive infinity. For negative numbers, if the next digit is from 0 through 4, the nearest number is toward positive infinity. If the next digit is from 6 through 9, the nearest number is toward negative infinity. - -If the next digit is from 0 through 4 or 6 through 9, the `MidpointRounding.AwayFromZero` and `MidpointRounding.ToEven` do not affect the result of the rounding operation. However, if the next digit is 5, which is the midpoint between two possible results, and all remaining digits are zero or there are no remaining digits, the nearest number is ambiguous. In this case, the round-to-nearest modes in `MidpointRounding` enable you to specify whether the rounding operation returns the nearest number away from zero or the nearest even number. - -The following table demonstrates the results of rounding some negative and positive numbers in conjunction with round-to-nearest modes. The precision used to round the numbers is zero, which means the number after the decimal point affects the rounding operation. For example, for the number -2.5, the digit after the decimal point is 5. Because that digit is the midpoint, you can use a `MidpointRounding` value to determine the result of rounding. If `AwayFromZero` is specified, -3 is returned because it is the nearest number away from zero with a precision of zero. If `ToEven` is specified, -2 is returned because it is the nearest even number with a precision of zero. - -| Original number | AwayFromZero | ToEven | -|-----------------|--------------|--------| -| 3.5 | 4 | 4 | -| 2.8 | 3 | 3 | -| 2.5 | 3 | 2 | -| 2.1 | 2 | 2 | -| -2.1 | -2 | -2 | -| -2.5 | -3 | -2 | -| -2.8 | -3 | -3 | -| -3.5 | -4 | -4 | - -## Directed rounding - -Fields: - -- -- -- - -A directed-rounding operation takes an original number with an implicit or specified precision and returns the next closest number in a specific direction with the same precision as the original number. Directed modes on `MidpointRounding` control toward which predefined number the rounding is performed. - -The following table demonstrates the results of rounding some negative and positive numbers in conjunction with directed-rounding modes. The precision used to round the numbers is zero, which means the number before the decimal point is affected by the rounding operation. - -| Original number | ToNegativeInfinity | ToPositiveInfinity | ToZero | -|-----------------|--------------------|--------------------|--------| -| 3.5 | 3 | 4 | 3 | -| 2.8 | 2 | 3 | 2 | -| 2.5 | 2 | 3 | 2 | -| 2.1 | 2 | 3 | 2 | -| -2.1 | -3 | -2 | -2 | -| -2.5 | -3 | -2 | -2 | -| -2.8 | -3 | -2 | -2 | -| -3.5 | -4 | -3 | -3 | diff --git a/docs/fundamentals/runtime-libraries/system-net-ftpwebrequest-proxy.md b/docs/fundamentals/runtime-libraries/system-net-ftpwebrequest-proxy.md deleted file mode 100644 index fd410315c206f..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-net-ftpwebrequest-proxy.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: System.Net.FtpWebRequest.Proxy property -description: Learn about the System.Net.FtpWebRequest.Proxy property. -ms.date: 01/24/2024 ---- -# System.Net.FtpWebRequest.Proxy property - -[!INCLUDE [context](includes/context.md)] - -> [!NOTE] -> This property is not supported on .NET Core, and setting it has no effect. Getting the property value returns `null`. - -The property identifies the instance that communicates with the FTP server. The proxy is set by the system by using configuration files and the Local Area Network settings. To specify that no proxy should be used, set to the proxy instance returned by the method. For more information about automatic proxy detection, see [Automatic Proxy Detection](/dotnet/framework/network-programming/automatic-proxy-detection). - -You must set before writing data to the request's stream or getting the response. Changing after calling the , , , or method causes an exception. - -The class supports HTTP and ISA Firewall Client proxies. - -If the specified proxy is an HTTP proxy, only the , , and commands are supported. diff --git a/docs/fundamentals/runtime-libraries/system-net-http-httpclient.md b/docs/fundamentals/runtime-libraries/system-net-http-httpclient.md deleted file mode 100644 index 38847f8b8502c..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-net-http-httpclient.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: System.Net.Http.HttpClient class -description: Learn about the System.Net.Http.HttpClient class. -ms.date: 12/31/2023 ---- -# System.Net.Http.HttpClient class - -[!INCLUDE [context](includes/context.md)] - -The class instance acts as a session to send HTTP requests. An instance is a collection of settings applied to all requests executed by that instance. In addition, every instance uses its own connection pool, isolating its requests from requests executed by other instances. - -## Instancing - - is intended to be instantiated once and reused throughout the life of an application. In .NET Core and .NET 5+, `HttpClient` pools connections inside the handler instance and reuses a connection across multiple requests. If you instantiate an `HttpClient` class for every request, the number of sockets available under heavy loads will be exhausted. This exhaustion will result in errors. - -You can configure additional options by passing in a "handler", such as (or in .NET Core 2.1 or later), as part of the constructor. The connection properties on the handler cannot be changed once a request has been submitted, so one reason to create a new `HttpClient` instance would be if you need to change the connection properties. If different requests require different settings, this may also lead to an application having multiple instances, where each instance is configured appropriately, and then requests are issued on the relevant client. - -`HttpClient` only resolves DNS entries when a connection is created. It does not track any time to live (TTL) durations specified by the DNS server. If DNS entries change regularly, which can happen in some container scenarios, the client won't respect those updates. To solve this issue, you can limit the lifetime of the connection by setting the property, so that DNS lookup is required when the connection is replaced. - -```csharp -public class GoodController : ApiController -{ - private static readonly HttpClient httpClient; - - static GoodController() - { - var socketsHandler = new SocketsHttpHandler - { - PooledConnectionLifetime = TimeSpan.FromMinutes(2) - }; - - httpClient = new HttpClient(socketsHandler); - } -} -``` - -As an alternative to creating only one `HttpClient` instance, you can also use to manage the `HttpClient` instances for you. For more information, see [Guidelines for using HttpClient](/dotnet/fundamentals/networking/httpclient-guidelines). - -## Derivation - -The also acts as a base class for more specific HTTP clients. An example would be a `FacebookHttpClient` that provides additional methods specific to a Facebook web service (for example, a `GetFriends` method). Derived classes should not override the virtual methods on the class. Instead, use a constructor overload that accepts to configure any pre-request or post-request processing. - -## Transports - -The is a high-level API that wraps the lower-level functionality available on each platform where it runs. - -On each platform, tries to use the best available transport: - -| **Host/Runtime** | **Backend** | -| --------------------------- | ----------------------------------------------------------------------------------------- | -| Windows/.NET Framework | | -| Windows/Mono | | -| Windows/UWP | Windows native (HTTP 2.0 capable) | -| Windows/.NET Core 1.0-2.0 | Windows native (HTTP 2.0 capable) | -| macOS/Mono | | -| macOS/.NET Core 1.0-2.0 | `libcurl`-based HTTP transport (HTTP 2.0 capable) | -| Linux/Mono | | -| Linux/.NET Core 1.0-2.0 | `libcurl`-based HTTP transport (HTTP 2.0 capable) | -| .NET Core 2.1 and later | | - -Users can also configure a specific transport for by invoking the constructor that takes an . - -### .NET Framework & Mono - -By default on .NET Framework and Mono, is used to send requests to the server. This behavior can be modified by specifying a different handler in one of the constructor overloads with an parameter. If you require features like authentication or caching, you can use to configure settings and the instance can be passed to the constructor. The returned handler can be passed to a constructor overload that has an parameter. - -### .NET Core - -Starting with .NET Core 2.1, the class instead of provides the implementation used by higher-level HTTP networking classes such as . The use of offers a number of advantages: - -- A significant performance improvement when compared with the previous implementation. -- The elimination of platform dependencies, which simplifies deployment and servicing. For example, `libcurl` is no longer a dependency on .NET Core for macOS and .NET Core for Linux. -- Consistent behavior across all .NET platforms. - -If this change is undesirable, on Windows you can continue to use by referencing its [NuGet package](https://www.nuget.org/packages/System.Net.Http.WinHttpHandler/) and passing it to [HttpClient's constructor](xref:System.Net.Http.HttpClient.%23ctor(System.Net.Http.HttpMessageHandler)) manually. - -## Configure behavior using runtime configuration options - -Certain aspects of 's behavior are customizable through [Runtime configuration options](/dotnet/core/run-time-config/networking). However, the behavior of these switches differs through .NET versions. For example, in .NET Core 2.1 - 3.1, you can configure whether is used by default, but that option is no longer available starting in .NET 5. - -## Connection pooling - -`HttpClient` pools HTTP connections where possible and uses them for more than one request. This can have a significant performance benefit, especially for HTTPS requests, as the connection handshake is only done once. - -Connection pool properties can be configured on a or passed in during construction, including , , and . - -Disposing of the `HttpClient` instance closes the open connections and cancels any pending requests. - -> [!NOTE] -> If you concurrently send HTTP/1.1 requests to the same server, new connections can be created. Even if you reuse the `HttpClient` instance, if the rate of requests is high, or if there are any firewall limitations, that can exhaust the available sockets because of default TCP cleanup timers. To limit the number of concurrent connections, you can set the `MaxConnectionsPerServer` property. By default, the number of concurrent HTTP/1.1 connections is unlimited. - -## Buffering and request lifetime - -By default, `HttpClient` methods (except ) buffer the responses from the server, reading all the response body into memory before returning the async result. Those requests will continue until one of the following occurs: - -- The succeeds and returns a result. -- The is reached, in which case the will be cancelled. -- The passable to some method overloads is fired. -- is called. -- The HttpClient is disposed. - -You can change the buffering behavior on a per-request basis using the parameter available on some method overloads. This argument can be used to specify if the should be considered complete after reading just the response headers, or after reading and buffering the response content. - -If your app that uses and related classes in the namespace intends to download large amounts of data (50 megabytes or more), then the app should stream those downloads and not use the default buffering. If you use the default buffering, the client memory usage will get very large, potentially resulting in substantially reduced performance. - -## Thread safety - -The following methods are thread safe: - -- -- -- -- -- -- -- -- -- - -## Proxies - -By default, `HttpClient` reads proxy configuration from environment variables or user/system settings, depending on the platform. You can change this behavior by passing a or to, in order of precedence: - -- The property on an `HttpClientHandler` passed in during `HttpClient` construction -- The static property (affects all instances) - -You can disable the proxy using . The default configuration for Windows users is to try and detect a proxy using network discovery, which can be slow. For high throughput applications where it's known that a proxy isn't required, you should disable the proxy. - -Proxy settings (like ) should be changed only before the first request is made using the `HttpClient`. Changes made after using the `HttpClient` for the first time may not be reflected in subsequent requests. - -## Timeouts - -You can use to set a default timeout for all HTTP requests from the `HttpClient` instance. The timeout only applies to the xxxAsync methods that cause a request/response to be initiated. If the timeout is reached, the for that request is cancelled. - -You can set some additional timeouts if you pass in a instance when constructing the `HttpClient` object: - -| Property | Description | -| ------------ | -------------- | -| | Specifies a timeout that's used when a request requires a new TCP connection to be created. If the timeout occurs, the request is cancelled. | -| | Specifies a timeout to be used for each connection in the connection pool. If the connection is idle, the connection is immediately closed; otherwise, the connection is closed at the end of the current request. | -| | If a connection in the connection pool is idle for this long, the connection is closed. | -| | If request has an "Expect: 100-continue" header, it delays sending content until the timeout or until a "100-continue" response is received. | - -`HttpClient` only resolves DNS entries when the connections are created. It does not track any time to live (TTL) durations specified by the DNS server. If DNS entries are changing regularly, which can happen in some container scenarios, you can use the to limit the lifetime of the connection so that DNS lookup is required when replacing the connection. diff --git a/docs/fundamentals/runtime-libraries/system-net-http-httpclienthandler.md b/docs/fundamentals/runtime-libraries/system-net-http-httpclienthandler.md deleted file mode 100644 index e74b161f4f5ab..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-net-http-httpclienthandler.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: System.Net.Http.HttpClientHandler class -description: Learn about the System.Net.Http.HttpClientHandler class. -ms.date: 12/31/2023 ---- -# System.Net.Http.HttpClientHandler class - -[!INCLUDE [context](includes/context.md)] - -The class and classes derived from it enable developers to configure a variety of options ranging from proxies to authentication. - -## HttpClientHandler in .NET Core - -Starting in .NET Core 2.1, the implementation of the `HttpClientHandler` class was changed to be based on the cross-platform HTTP protocol stack used by the class. Prior to .NET Core 2.1, the `HttpClientHandler` class used older HTTP protocol stacks ( on Windows and `CurlHandler`, an internal class implemented on top of Linux's native `libcurl` component, on Linux). diff --git a/docs/fundamentals/runtime-libraries/system-net-httplistener.md b/docs/fundamentals/runtime-libraries/system-net-httplistener.md deleted file mode 100644 index 2ab06509f7bf2..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-net-httplistener.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: System.Net.HttpListener class -description: Learn about the System.Net.HttpListener class. -ms.date: 12/31/2023 ---- -# System.Net.HttpListener class - -[!INCLUDE [context](includes/context.md)] - -Using the class, you can create a simple HTTP protocol listener that responds to HTTP requests. The listener is active for the lifetime of the object and runs within your application with its permissions. - -To use , create a new instance of the class using the constructor and use the property to gain access to the collection that holds the strings that specify which Uniform Resource Identifier (URI) prefixes the should process. - -A URI prefix string is composed of a scheme (http or https), a host, an optional port, and an optional path. An example of a complete prefix string is `http://www.contoso.com:8080/customerData/`. Prefixes must end in a forward slash ("/"). The object with the prefix that most closely matches a requested URI responds to the request. Multiple objects cannot add the same prefix; a exception is thrown if a adds a prefix that is already in use. - -When a port is specified, the host element can be replaced with "\*" to indicate that the accepts requests sent to the port if the requested URI does not match any other prefix. For example, to receive all requests sent to port 8080 when the requested URI is not handled by any , the prefix is *http://\*:8080/*. Similarly, to specify that the accepts all requests sent to a port, replace the host element with the "+" character. For example, *https://+:8080*. The "\*" and "+" characters can be present in prefixes that include paths. - -Wildcard subdomains are supported in URI prefixes that are managed by an object. To specify a wildcard subdomain, use the "\*" character as part of the hostname in a URI prefix. For example, *http://\*.foo.com/*. Pass this as the argument to the method. - -> [!WARNING] -> Top-level wildcard bindings (*http://\*:8080/* and *http://+:8080*) should **not** be used. Top-level wildcard bindings can open up your app to security vulnerabilities. This applies to both strong and weak wildcards. Use explicit host names rather than wildcards. Subdomain wildcard binding (for example, `*.mysub.com`) doesn't have this security risk if you control the entire parent domain (as opposed to `*.com`, which is vulnerable). See [rfc7230 section-5.4](https://tools.ietf.org/html/rfc7230#section-5.4) for more information. - -To begin listening for requests from clients, add the URI prefixes to the collection and call the method. offers both synchronous and asynchronous models for processing client requests. Requests and their associated responses are accessed using the object returned by the method or its asynchronous counterparts, the and methods. - -The synchronous model is appropriate if your application should block while waiting for a client request and if you want to process only one request at a time. Using the synchronous model, call the method, which waits for a client to send a request. The method returns an object to you for processing when one occurs. - -In the more complex asynchronous model, your application does not block while waiting for requests and each request is processed in its own execution thread. Use the method to specify an application-defined method to be called for each incoming request. Within that method, call the method to obtain the request, process it, and respond. - -In either model, incoming requests are accessed using the property and are represented by objects. Similarly, responses are accessed using the property and are represented by objects. These objects share some functionality with the and objects, but the latter objects cannot be used in conjunction with because they implement client, not server, behaviors. - -An can require client authentication. You can either specify a particular scheme to use for authentication, or you can specify a delegate that determines the scheme to use. You must require some form of authentication to obtain information about the client's identity. For additional information, see the , , and properties. - -> [!NOTE] -> If you create an using https, you must select a Server Certificate for that listener. Otherwise, requests to this will fail with an unexpected close of the connection. - -> [!NOTE] -> You can configure Server Certificates and other listener options by using Network Shell (netsh.exe). See [Network Shell (Netsh)](/windows-server/networking/technologies/netsh/netsh) for more details. The executable began shipping with Windows Server 2008 and Windows Vista. - -> [!NOTE] -> If you specify multiple authentication schemes for the , the listener will challenge clients in the following order: `Negotiate`, `NTLM`, `Digest`, and then `Basic`. - -## HTTP.sys - -The class is built on top of `HTTP.sys`, which is the kernel mode listener that handles all HTTP traffic for Windows. -`HTTP.sys` provides connection management, bandwidth throttling, and web server logging. -Use the [HttpCfg.exe](/windows/win32/http/httpcfg-exe) tool to add SSL certificates. - -Starting in .NET 11, the Windows `HTTP.sys` implementation of supports enabling kernel-level response buffering. When enabled, response data is buffered by `HTTP.sys` before being sent to the client, which can improve throughput for high-latency connections. This can be enabled by calling the method as follows: - - ```csharp - AppContext.SetSwitch("System.Net.HttpListener.EnableKernelResponseBuffering", true); - ``` diff --git a/docs/fundamentals/runtime-libraries/system-net-sockets-socket.md b/docs/fundamentals/runtime-libraries/system-net-sockets-socket.md deleted file mode 100644 index 8336cf59d819e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-net-sockets-socket.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: System.Net.Sockets.Socket class -description: Learn about the System.Net.Sockets.Socket class. -ms.date: 12/31/2023 ---- -# System.Net.Sockets.Socket class - -[!INCLUDE [context](includes/context.md)] - -The class provides a rich set of methods and properties for network communications. The class allows you to perform both synchronous and asynchronous data transfer using any of the communication protocols listed in the enumeration. - -The class follows the .NET naming pattern for asynchronous methods. For example, the synchronous method corresponds to the asynchronous variants. - -Use the following methods for synchronous operation mode: - -- If you are using a connection-oriented protocol such as TCP, your server can listen for connections using the method. The method processes any incoming connection requests and returns a that you can use to communicate data with the remote host. Use this returned to call the or method. Call the method prior to calling the method if you want to specify the local IP address and port number. Use a port number of zero if you want the underlying service provider to assign a free port for you. If you want to connect to a listening host, call the method. To communicate data, call the or method. -- If you are using a connectionless protocol such as UDP, you do not need to listen for connections at all. Call the method to accept any incoming datagrams. Use the method to send datagrams to a remote host. - -To process communications asynchronously, use the following methods: - -- If you are using a connection-oriented protocol such as TCP, use to connect with a listening host. Use or to communicate data asynchronously. Incoming connection requests can be processed using . -- If you are using a connectionless protocol such as UDP, you can use to send datagrams, and to receive datagrams. - -If you perform multiple asynchronous operations on a socket, they do not necessarily complete in the order in which they are started. - -When you are finished sending and receiving data, use the method to disable the . After calling , call the method to release all resources associated with the . - -The class allows you to configure your using the method. Retrieve these settings using the method. diff --git a/docs/fundamentals/runtime-libraries/system-notimplementedexception.md b/docs/fundamentals/runtime-libraries/system-notimplementedexception.md deleted file mode 100644 index 1482a8bb1f7fd..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-notimplementedexception.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: System.NotImplementedException class -description: Learn about the System.NotImplementedException class. -ms.date: 12/31/2023 ---- -# System.NotImplementedException class - -[!INCLUDE [context](includes/context.md)] - -The exception is thrown when a particular method, get accessor, or set accessor is present as a member of a type but is not implemented. - - uses the default implementation, which supports reference equality. For a list of initial values for an instance of , see the constructors. - -## Throw the exception - -You might choose to throw a exception in properties or methods in your own types when the that member is still in development and will only later be implemented in production code. In other words, a exception should be synonymous with "still in development." - -## Handle the exception - -The exception indicates that the method or property that you are attempting to invoke has no implementation and therefore provides no functionality. As a result, you should not handle this error in a `try/catch` block. Instead, you should remove the member invocation from your code. You can include a call to the member when it is implemented in the production version of a library. - -In some cases, a exception may not be used to indicate functionality that is still in development in a pre-production library. However, this still indicates that the functionality is unavailable, and you should remove the member invocation from your code. - -## NotImplementedException and other exception types - -.NET also includes two other exception types, and , that indicate that no implementation exists for a particular member of a type. You should throw one of these instead of a exception under the following conditions: - -- Throw a exception on platforms on which the functionality is not supported if you've designed a type with one or more members that are available on some platforms or versions but not others. -- Throw a exception if the implementation of an interface member or an override to an abstract base class method is not possible. - - For example, the method throws a exception because no meaningful conversion between a date and time and a 32-bit signed integer exists. The method must be present in this case because the class implements the interface. - -You should also throw a exception if you've implemented an abstract base class and add a new member to it that must be overridden by derived classes. In that case, making the member abstract causes existing subclasses to fail to load. diff --git a/docs/fundamentals/runtime-libraries/system-notsupportedexception.md b/docs/fundamentals/runtime-libraries/system-notsupportedexception.md deleted file mode 100644 index 0b92fee662638..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-notsupportedexception.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: System.NotSupportedException class -description: Learn about the System.NotSupportedException class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB - - FSharp ---- -# System.NotSupportedException class - -[!INCLUDE [context](includes/context.md)] - - indicates that no implementation exists for an invoked method or property. - - uses the HRESULT `COR_E_NOTSUPPORTED`, which has the value 0x80131515. - -For a list of initial property values for an instance of , see the constructors. - -## Throw a NotSupportedException exception - -You might consider throwing a exception in the following cases: - -- You're implementing a general-purpose interface, and number of the methods have no meaningful implementation. For example, if you are creating a date and time type that implements the interface, you would throw a exception for most of the conversions. - -- You've inherited from an abstract class that requires that you override a number of methods. However, you're only prepared to provide an implementation for a subset of these. For the methods that you decide not to implement, you can choose to throw a . - -- You're defining a general-purpose type with a state that enables operations conditionally. For example, your type can be either read-only or read-write. In that case: - - - If the object is read-only, attempting to assign values to the properties of an instance or call methods that modify instance state should throw a exception. - - - You should implement a property that returns a value that indicates whether particular functionality is available. For example, for a type that can be either read-only or read-write, you could implement a `IsReadOnly` property that indicates whether the set of read-write methods are available or unavailable. - -## Handle a NotSupportedException exception - -The exception indicates that a method has no implementation and that you should not call it. You should not handle the exception. Instead, what you should do depends on the cause of the exception: whether an implementation is completely absent, or the member invocation is inconsistent with the purpose of an object (such as a call to the method on a read-only object). - -**An implementation has not been provided because the operation cannot be performed in a meaningful way.** -This is a common exception when you are calling methods on an object that provides implementations for the methods of an abstract base class, or that implements a general-purpose interface, and the method has no meaningful implementation. - -For example, the class implements the interface, which means that it must include a method to convert every primitive type to every other primitive type. Many of those conversions, however, are not possible. As a result, a call to the method, for instance, throws a exception because there is no possible conversion between a and a value - -To eliminate the exception, you should eliminate the method call. - -**The method call is not supported given the state of the object.** -You're attempting to invoke a member whose functionality is unavailable because of the object's state. You can eliminate the exception in one of three ways: - -- You know the state of the object in advance, but you've invoked an unsupported method or property. In this case, the member invocation is an error, and you can eliminate it. - -- You know the state of the object in advance (usually because your code has instantiated it), but the object is mis-configured. The following example illustrates this issue. It creates a read-only object and then attempts to write to it. - - :::code language="csharp" source="./snippets/System/NotSupportedException/Overview/csharp/BadState1.cs" id="Snippet1"::: - :::code language="fsharp" source="./snippets/System/NotSupportedException/Overview/fsharp/BadState1.fs" id="Snippet1"::: - :::code language="vb" source="./snippets/System/NotSupportedException/Overview/vb/BadState1.vb" id="Snippet1"::: - - Ycan eliminate the exception by ensuring that the instantiated object supports the functionality you intend. The following example addresses the problem of the read-only object by providing the correct arguments to the constructor. - -- You don't know the state of the object in advance, and the object doesn't support a particular operation. In most cases, the object should include a property or method that indicates whether it supports a particular set of operations. You can eliminate the exception by checking the value of the object and invoking the member only if appropriate. - - The following example defines a `DetectEncoding` method that throws a exception when it attempts to read from the beginning of a stream that does not support read access. - - :::code language="csharp" source="./snippets/System/NotSupportedException/Overview/csharp/TestProp1.cs" id="Snippet3"::: - :::code language="fsharp" source="./snippets/System/NotSupportedException/Overview/fsharp/TestProp1.fs" id="Snippet3"::: - :::code language="vb" source="./snippets/System/NotSupportedException/Overview/vb/TestProp1.vb" id="Snippet3"::: - - You can eliminate the exception by examining the value of the property and exiting the method if the stream is read-only. - - :::code language="csharp" source="./snippets/System/NotSupportedException/Overview/csharp/TestProp2.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System/NotSupportedException/Overview/fsharp/TestProp2.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System/NotSupportedException/Overview/vb/TestProp2.vb" id="Snippet4"::: - -## Related exception types - -The exception is closely related to two other exception types; - -- - - This exception is thrown when a method could be implemented but is not, either because the member will be implemented in a later version, the member is not available on a particular platform, or the member belongs to an abstract class and a derived class must provide an implementation. - -- - - This exception is thrown in scenarios in which it is generally sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed. - -## .NET Compact Framework notes - -When working with the .NET Compact Framework and using P/Invoke on a native function, this exception may be thrown if: - -- The declaration in managed code is incorrect. -- The .NET Compact Framework does not support what you are trying to do. -- The DLL names are mangled on export. - -If a exception is thrown, check: - -- For any violations of the .NET Compact Framework P/Invoke restrictions. -- For any arguments that require pre-allocated memory. If these exist, you should pass a reference to an existing variable. -- That the names of the exported functions are correct. This can be verified with [DumpBin.exe](/cpp/build/reference/dumpbin-reference). -- That you are not attempting to pass too many arguments. diff --git a/docs/fundamentals/runtime-libraries/system-nullable.md b/docs/fundamentals/runtime-libraries/system-nullable.md deleted file mode 100644 index cdca18a5141bf..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-nullable.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: System.Nullable class -description: Learn about the System.Nullable class. -ms.date: 12/31/2023 ---- -# System.Nullable class - -[!INCLUDE [context](includes/context.md)] - -The class supports value types that can be assigned `null`. - -A type is said to be nullable if it can be assigned a value or can be assigned `null`, which means the type has no value whatsoever. By default, all reference types, such as , are nullable, but all value types, such as , are not. - -In C# and Visual Basic, you mark a value type as nullable by using the `?` notation after the value type. For example, `int?` in C# or `Integer?` in Visual Basic declares an integer value type that can be assigned `null`. - -The class provides complementary support for the structure. The class supports obtaining the underlying type of a nullable type, and comparison and equality operations on pairs of nullable types whose underlying value type does not support generic comparison and equality operations. - -## Boxing and unboxing - -When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the object, not the object itself. That is, if the property is `true`, the contents of the property is boxed. - -If the `HasValue` property of a nullable type is `false`, the result of the boxing operation is `null`. When the underlying value of a nullable type is unboxed, the common language runtime creates a new structure initialized to the underlying value. diff --git a/docs/fundamentals/runtime-libraries/system-nullable{t}.md b/docs/fundamentals/runtime-libraries/system-nullable{t}.md deleted file mode 100644 index 8ca0e837bebaf..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-nullable{t}.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: System.Nullable structure -description: Learn about the System.Nullable structure. -ms.date: 10/31/2024 ---- -# System.Nullable\ structure - -[!INCLUDE [context](includes/context.md)] - -The class represents a value type that can be assigned `null`. - -A type is said to be nullable if it can be assigned a value or can be assigned `null`, which means the type has no value whatsoever. By default, all reference types, such as , are nullable, but all value types, such as , are not. - -In C# and Visual Basic, you mark a value type as nullable by using the `?` notation after the value type. For example, `int?` in C# or `Integer?` in Visual Basic declares an integer value type that can be assigned `null`. - -The structure supports using only a value type as a nullable type because reference types are nullable by design. - -The class provides complementary support for the structure. The class supports obtaining the underlying type of a nullable type, and comparison and equality operations on pairs of nullable types whose underlying value type does not support generic comparison and equality operations. - -## Fundamental properties - -The two fundamental members of the structure are the and properties. If the property for a object is `true`, the value of the object can be accessed with the property. If the property is `false`, the value of the object is undefined and an attempt to access the property throws an . - -## Boxing and unboxing - -When a nullable type is boxed, the common language runtime automatically boxes the underlying value of the object, not the object itself. That is, if the property is `true`, the contents of the property is boxed. When the underlying value of a nullable type is unboxed, the common language runtime creates a new structure initialized to the underlying value. - -If the `HasValue` property of a nullable type is `false`, the result of a boxing operation is `null`. Consequently, if a boxed nullable type is passed to a method that expects an object argument, that method must be prepared to handle the case where the argument is `null`. When `null` is unboxed into a nullable type, the common language runtime creates a new structure and initializes its `HasValue` property to `false`. - -## Windows runtime components - -You can include a type as a member of a structure exported in a WinMD library. diff --git a/docs/fundamentals/runtime-libraries/system-numerics-biginteger.md b/docs/fundamentals/runtime-libraries/system-numerics-biginteger.md deleted file mode 100644 index 64c5a0d346c9e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-numerics-biginteger.md +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: System.Numerics.BigInteger struct -description: Learn about the System.Numerics.BigInteger struct. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Numerics.BigInteger struct - -[!INCLUDE [context](includes/context.md)] - -The type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds. The members of the type closely parallel those of other integral types (the , , , , , , , and types). This type differs from the other integral types in .NET, which have a range indicated by their `MinValue` and `MaxValue` properties. - -> [!NOTE] -> Because the type is immutable (see [Mutability](#mutability)) and because it has no upper or lower bounds, an can be thrown for any operation that causes a value to grow too large. - -## Instantiate a BigInteger object - -You can instantiate a object in several ways: - -- You can use the `new` keyword and provide any integral or floating-point value as a parameter to the constructor. (Floating-point values are truncated before they are assigned to the .) The following example illustrates how to use the `new` keyword to instantiate values. - - :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs" id="Snippet1"::: - :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/BigInteger_Examples.vb" id="Snippet1"::: - -- You can declare a variable and assign it a value just as you would any numeric type, as long as that value is an integral type. The following example uses assignment to create a value from an . - - :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs" id="Snippet2"::: - :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/BigInteger_Examples.vb" id="Snippet2"::: - -- You can assign a decimal or floating-point value to a object if you cast the value or convert it first. The following example explicitly casts (in C#) or converts (in Visual Basic) a and a value to a . - - :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs" id="Snippet3"::: - :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/BigInteger_Examples.vb" id="Snippet3"::: - -These methods enable you to instantiate a object whose value is in the range of one of the existing numeric types only. You can instantiate a object whose value can exceed the range of the existing numeric types in one of three ways: - -- You can use the `new` keyword and provide a byte array of any size to the constructor. For example: - - :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs" id="Snippet4"::: - :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/BigInteger_Examples.vb" id="Snippet4"::: - -- You can call the or methods to convert the string representation of a number to a . For example: - - :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs" id="Snippet5"::: - :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/BigInteger_Examples.vb" id="Snippet5"::: - -- You can call a `static` (`Shared` in Visual Basic) method that performs some operation on a numeric expression and returns a calculated result. The following example does this by cubing and assigning the result to a . - - :::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/BigInteger_Examples.cs" id="Snippet6"::: - :::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/BigInteger_Examples.vb" id="Snippet6"::: - -The uninitialized value of a is . - -## Perform operations on BigInteger values - -You can use a instance as you would use any other integral type. overloads the standard numeric operators to enable you to perform basic mathematical operations such as addition, subtraction, division, multiplication, and unary negation. You can also use the standard numeric operators to compare two values with each other. Like the other integral types, also supports the bitwise `And`, `Or`, `XOr`, left shift, and right shift operators. For languages that do not support custom operators, the structure also provides equivalent methods for performing mathematical operations. These include , , , , , and several others. - -Many members of the structure correspond directly to members of the other integral types. In addition, adds members such as the following: - -- , which returns a value that indicates the sign of a value. - -- , which returns the absolute value of a value. - -- , which returns both the quotient and remainder of a division operation. - -- , which returns the greatest common divisor of two values. - -Many of these additional members correspond to the members of the class, which provides the functionality to work with the primitive numeric types. - -## Mutability - -The following example instantiates a object and then increments its value by one. - -:::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/Mutability_Examples.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/Mutability_Examples.vb" id="Snippet1"::: - -Although this example appears to modify the value of the existing object, this is not the case. objects are immutable, which means that internally, the common language runtime actually creates a new object and assigns it a value one greater than its previous value. This new object is then returned to the caller. - -> [!NOTE] -> The other numeric types in .NET are also immutable. However, because the type has no upper or lower bounds, its values can grow extremely large and have a measurable impact on performance. - -Although this process is transparent to the caller, it does incur a performance penalty. In some cases, especially when repeated operations are performed in a loop on very large values, that performance penalty can be significant. For example, in the following example, an operation is performed repetitively up to a million times, and a value is incremented by one every time the operation succeeds. - -:::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/Mutability_Examples.cs" id="Snippet12"::: -:::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/Mutability_Examples.vb" id="Snippet12"::: - -In such a case, you can improve performance by performing all intermediate assignments to an variable. The final value of the variable can then be assigned to the object when the loop exits. The following example provides an illustration. - -:::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/Mutability_Examples.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/Mutability_Examples.vb" id="Snippet3"::: - -## Byte arrays and hexadecimal strings - -If you convert values to byte arrays, or if you convert byte arrays to values, you must consider the order of bytes. The structure expects the individual bytes in a byte array to appear in little-endian order (that is, the lower-order bytes of the value precede the higher-order bytes). You can round-trip a value by calling the method and then passing the resulting byte array to the constructor, as the following example shows. - -:::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples.vb" id="Snippet1"::: - -To instantiate a value from a byte array that represents a value of some other integral type, you can pass the integral value to the method, and then pass the resulting byte array to the constructor. The following example instantiates a value from a byte array that represents an value. - -:::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples.vb" id="Snippet2"::: - -The structure assumes that negative values are stored by using two's complement representation. Because the structure represents a numeric value with no fixed length, the constructor always interprets the most significant bit of the last byte in the array as a sign bit. To prevent the constructor from confusing the two's complement representation of a negative value with the sign and magnitude representation of a positive value, positive values in which the most significant bit of the last byte in the byte array would ordinarily be set should include an additional byte whose value is 0. For example, 0xC0 0xBD 0xF0 0xFF is the little-endian hexadecimal representation of either -1,000,000 or 4,293,967,296. Because the most significant bit of the last byte in this array is on, the value of the byte array would be interpreted by the constructor as -1,000,000. To instantiate a whose value is positive, a byte array whose elements are 0xC0 0xBD 0xF0 0xFF 0x00 must be passed to the constructor. The following example illustrates this. - -:::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples.vb" id="Snippet3"::: - -Byte arrays created by the method from positive values include this extra zero-value byte. Therefore, the structure can successfully round-trip values by assigning them to, and then restoring them from, byte arrays, as the following example shows. - -:::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs" id="Snippet4"::: -:::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples.vb" id="Snippet4"::: - -However, you may need to add this additional zero-value byte to byte arrays that are created dynamically by the developer or that are returned by methods that convert unsigned integers to byte arrays (such as , , and ). - -When parsing a hexadecimal string, the and methods assume that if the most significant bit of the first byte in the string is set, or if the first hexadecimal digit of the string represents the lower four bits of a byte value, the value is represented by using two's complement representation. For example, both "FF01" and "F01" represent the decimal value -255. To differentiate positive from negative values, positive values should include a leading zero. The relevant overloads of the method, when they are passed the "X" format string, add a leading zero to the returned hexadecimal string for positive values. This makes it possible to round-trip values by using the and methods, as the following example shows. - -:::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples.cs" id="Snippet5"::: -:::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples.vb" id="Snippet5"::: - -However, the hexadecimal strings created by calling the `ToString` methods of the other integral types or the overloads of the method that include a `toBase` parameter do not indicate the sign of the value or the source data type from which the hexadecimal string was derived. Successfully instantiating a value from such a string requires some additional logic. The following example provides one possible implementation. - -:::code language="csharp" source="./snippets/System.Numerics/BigInteger/Overview/csharp/ByteAndHex_Examples2.cs" id="Snippet6"::: -:::code language="vb" source="./snippets/System.Numerics/BigInteger/Overview/vb/ByteAndHex_Examples2.vb" id="Snippet6"::: diff --git a/docs/fundamentals/runtime-libraries/system-numerics-complex.md b/docs/fundamentals/runtime-libraries/system-numerics-complex.md deleted file mode 100644 index 2ea9dd2938159..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-numerics-complex.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: System.Numerics.Complex struct -description: Learn about the System.Numerics.Complex struct. -ms.date: 05/15/2025 -dev_langs: - - CSharp - - VB ---- -# System.Numerics.Complex struct - -[!INCLUDE [context](includes/context.md)] - -A complex number is a number that comprises a real number part and an imaginary number part. A complex number z is usually written in the form `z = x + yi`, where *x* and *y* are real numbers, and *i* is the imaginary unit that has the property *i*2 = -1. The real part of the complex number is represented by *x*, and the imaginary part of the complex number is represented by *y*. - -The type uses the Cartesian coordinate system (real, imaginary) when instantiating and manipulating complex numbers. A complex number can be represented as a point in a two-dimensional coordinate system, which is known as the complex plane. The real part of the complex number is positioned on the x-axis (the horizontal axis), and the imaginary part is positioned on the y-axis (the vertical axis). - -Any point in the complex plane can also be expressed based on its absolute value, by using the polar coordinate system. In polar coordinates, a point is characterized by two numbers: - -- Its magnitude, which is the distance of the point from the origin (that is, 0,0, or the point at which the x-axis and the y-axis intersect). -- Its phase, which is the angle between the real axis and the line drawn from the origin to the point. - -## Instantiate a complex number - -You can assign a value to a complex number in one of the following ways: - -- By passing two values to its constructor. The first value represents the real part of the complex number, and the second value represents its imaginary part. These values represent the position of the complex number in the two-dimensional Cartesian coordinate system. - -- By calling the static (`Shared` in Visual Basic) method to create a complex number from its polar coordinates. - -- By assigning a , , , , , , , , , or value to a object. The value becomes the real part of the complex number, and its imaginary part equals 0. - -- By casting (in C#) or converting (in Visual Basic) a or value to a object. The value becomes the real part of the complex number, and its imaginary part equals 0. - -- By assigning the complex number that is returned by a method or operator to a object. For example, is a static method that returns a complex number that is the sum of two complex numbers, and the operator adds two complex numbers and returns the result. - -The following example demonstrates each of these five ways of assigning a value to a complex number. - -:::code language="csharp" source="./snippets/System.Numerics/Complex/Overview/csharp/create1.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Numerics/Complex/Overview/vb/create1.vb" id="Snippet2"::: - -## Operations with complex numbers - -The structure in .NET includes members that provide the following functionality: - -- Methods to compare two complex numbers to determine whether they are equal. -- Operators to perform arithmetic operations on complex numbers. operators enable you to perform addition, subtraction, multiplication, division, and unary negation with complex numbers. -- Methods to perform other numerical operations on complex numbers. In addition to the four basic arithmetic operations, you can raise a complex number to a specified power, find the square root of a complex number, and get the absolute value of a complex number. -- Methods to perform trigonometric operations on complex numbers. For example, you can calculate the tangent of an angle represented by a complex number. - -Note that, because the and properties are read-only, you cannot modify the value of an existing object. All methods that perform an operation on a number, if their return value is of type , return a new number. - -## Precision and complex numbers - -The real and imaginary parts of a complex number are represented by two double-precision floating-point values. This means that values, like double-precision floating-point values, can lose precision as a result of numerical operations. This means that strict comparisons for equality of two values may fail, even if the difference between the two values is due to a loss of precision. For more information, see . - -For example, performing exponentiation on the logarithm of a number should return the original number. However, in some cases, the loss of precision of floating-point values can cause slight differences between the two values, as the following example illustrates. - -:::code language="csharp" source="./snippets/System.Numerics/Complex/Overview/csharp/precision1.cs" id="Snippet5"::: -:::code language="vb" source="./snippets/System.Numerics/Complex/Overview/vb/precision1.vb" id="Snippet5"::: - -Similarly, the following example, which calculates the square root of a number, produces slightly different results on the 32-bit and IA64 versions of .NET. - -:::code language="csharp" source="./snippets/System.Numerics/Complex/Overview/csharp/precision1.cs" id="Snippet6"::: -:::code language="vb" source="./snippets/System.Numerics/Complex/Overview/vb/precision1.vb" id="Snippet6"::: - -## Infinity and NaN - -The real and imaginary parts of a complex number are represented by values. In addition to ranging from to , the real or imaginary part of a complex number can have a value of , , or . , , and all propagate in any arithmetic or trigonometric operation. - -In the following example, division by produces a complex number whose real and imaginary parts are both . As a result, performing multiplication with this value also produces a complex number whose real and imaginary parts are . Similarly, performing a multiplication that overflows the range of the type produces a complex number whose real part is and whose imaginary part is . Subsequently performing division with this complex number returns a complex number whose real part is and whose imaginary part is . - -:::code language="csharp" source="./snippets/System.Numerics/Complex/Overview/csharp/nan1.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Numerics/Complex/Overview/vb/nan1.vb" id="Snippet3"::: - -Mathematical operations with complex numbers that are invalid or that overflow the range of the data type do not throw an exception. Instead, they return a , , or under the following conditions: - -- The division of a positive number by zero returns . -- Any operation that overflows the upper bound of the data type returns . -- The division of a negative number by zero returns . -- Any operation that overflows the lower bound of the data type returns . -- The division of a zero by zero returns . -- Any operation that is performed on operands whose values are , , or returns , , or , depending on the specific operation. - -Note that this applies to any intermediate calculations performed by a method. For example, the multiplication of `new Complex(9e308, 9e308) and new Complex(2.5, 3.5)` uses the formula (ac - bd) + (ad + bc)i. The calculation of the real component that results from the multiplication evaluates the expression 9e308 *2.5 - 9e308* 3.5. Each intermediate multiplication in this expression returns , and the attempt to subtract from returns . - -## Format a complex number - -By default, the string representation of a complex number takes the form `<`*real*`;` *imaginary*`>`, where *real* and *imaginary* are the string representations of the values that form the complex number's real and imaginary components. Some overloads of the method allow customization of the string representations of these values to reflect the formatting conventions of a particular culture or to appear in a particular format defined by a standard or custom numeric format string. (For more information, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md).) - -One of the more common ways of expressing the string representation of a complex number takes the form `a + bi`, where `a` is the complex number's real component, and `b` is the complex number's imaginary component. In electrical engineering, a complex number is most commonly expressed as `a + bj`. You can return the string representation of a complex number in either of these two forms. To do this, define a custom format provider by implementing the and interfaces, and then call the method. - -The following example defines a `ComplexFormatter` class that represents a complex number as a string in the form of either `a + bi` or `a + bj`. - -:::code language="csharp" source="./snippets/System.Numerics/Complex/Overview/csharp/customfmt1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Numerics/Complex/Overview/vb/customfmt1.vb" id="Snippet1"::: - -The following example then uses this custom formatter to display the string representation of a complex number. - -:::code language="csharp" source="./snippets/System.Numerics/Complex/Overview/csharp/customfmt1.cs" id="Snippet4"::: -:::code language="vb" source="./snippets/System.Numerics/Complex/Overview/vb/customfmt1.vb" id="Snippet4"::: diff --git a/docs/fundamentals/runtime-libraries/system-object-equals.md b/docs/fundamentals/runtime-libraries/system-object-equals.md deleted file mode 100644 index 40ec1e8eae486..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-object-equals.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: System.Object.Equals method -description: Learn about the System.Object.Equals method. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Object.Equals method - -[!INCLUDE [context](includes/context.md)] - -This article pertains to the method. - -The type of comparison between the current instance and the `obj` parameter depends on whether the current instance is a reference type or a value type. - -- If the current instance is a reference type, the method tests for reference equality, and a call to the method is equivalent to a call to the method. Reference equality means that the object variables that are compared refer to the same object. The following example illustrates the result of such a comparison. It defines a `Person` class, which is a reference type, and calls the `Person` class constructor to instantiate two new `Person` objects, `person1a` and `person2`, which have the same value. It also assigns `person1a` to another object variable, `person1b`. As the output from the example shows, `person1a` and `person1b` are equal because they reference the same object. However, `person1a` and `person2` are not equal, although they have the same value. - - :::code language="csharp" source="./snippets/System/Object/Equals/csharp/equals_ref.cs" id="Snippet2"::: - :::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals_ref.fs" id="Snippet2"::: - :::code language="vb" source="./snippets/System/Object/Equals/vb/equals_ref.vb" id="Snippet2"::: - -- If the current instance is a value type, the method tests for value equality. Value equality means the following: - - - The two objects are of the same type. As the following example shows, a object that has a value of 12 does not equal an object that has a value of 12, because the two objects have different runtime types. - - :::code language="csharp" source="./snippets/System/Object/Equals/csharp/equals_val1.cs" id="Snippet3"::: - :::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals_val1.fs" id="Snippet3"::: - :::code language="vb" source="./snippets/System/Object/Equals/vb/equals_val1.vb" id="Snippet3"::: - - - The values of the public and private fields of the two objects are equal. The following example tests for value equality. It defines a `Person` structure, which is a value type, and calls the `Person` class constructor to instantiate two new `Person` objects, `person1` and `person2`, which have the same value. As the output from the example shows, although the two object variables refer to different objects, `person1` and `person2` are equal because they have the same value for the private `personName` field. - - :::code language="csharp" source="./snippets/System/Object/Equals/csharp/equals_val2.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals_val2.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System/Object/Equals/vb/equals_val2.vb" id="Snippet4"::: - -Because the class is the base class for all types in .NET, the method provides the default equality comparison for all other types. However, types often override the method to implement value equality. For more information, see the Notes for Callers and Notes for Inheritors sections. - -## Notes for the Windows Runtime - -When you call the method overload on a class in the Windows Runtime, it provides the default behavior for classes that don't override . This is part of the support that .NET provides for the Windows Runtime (see [.NET Support for Windows Store Apps and Windows Runtime](/dotnet/standard/cross-platform/support-for-windows-store-apps-and-windows-runtime)). Classes in the Windows Runtime don't inherit , and currently don't implement an method. However, they appear to have , , and methods when you use them in your C# or Visual Basic code, and .NET provides the default behavior for these methods. - -> [!NOTE] -> Windows Runtime classes that are written in C# or Visual Basic can override the method overload. - -## Notes for callers - -Derived classes frequently override the method to implement value equality. In addition, types also frequently provide an additional strongly typed overload to the `Equals` method, typically by implementing the interface. When you call the `Equals` method to test for equality, you should know whether the current instance overrides and understand how a particular call to an `Equals` method is resolved. Otherwise, you may be performing a test for equality that is different from what you intended, and the method may return an unexpected value. - -The following example provides an illustration. It instantiates three objects with identical strings, and then makes four calls to `Equals` methods. The first method call returns `true`, and the remaining three return `false`. - -:::code language="csharp" source="./snippets/System/Object/Equals/csharp/equalssb1.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equalssb1.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/Object/Equals/vb/equalssb1.vb" id="Snippet5"::: - -In the first case, the strongly typed method overload, which tests for value equality, is called. Because the strings assigned to the two objects are equal, the method returns `true`. However, does not override . Because of this, when the object is cast to an , when a instance is assigned to a variable of type , and when the method is passed two objects, the default method is called. Because is a reference type, this is equivalent to passing the two objects to the method. Although all three objects contain identical strings, they refer to three distinct objects. As a result, these three method calls return `false`. - -You can compare the current object to another object for reference equality by calling the method. In Visual Basic, you can also use the `is` keyword (for example, `If Me Is otherObject Then ...`). - -## Notes for inheritors - -When you define your own type, that type inherits the functionality defined by the `Equals` method of its base type. The following table lists the default implementation of the `Equals` method for the major categories of types in .NET. - -|Type category|Equality defined by|Comments| -|-------------------|-------------------------|--------------| -|Class derived directly from ||Reference equality; equivalent to calling .| -|Structure||Value equality; either direct byte-by-byte comparison or field-by-field comparison using reflection.| -|Enumeration||Values must have the same enumeration type and the same underlying value.| -|Delegate||Delegates must have the same type with identical invocation lists.| -|Interface||Reference equality.| - -For a value type, you should always override , because tests for equality that rely on reflection offer poor performance. You can also override the default implementation of for reference types to test for value equality instead of reference equality and to define the precise meaning of value equality. Such implementations of return `true` if the two objects have the same value, even if they are not the same instance. The type's implementer decides what constitutes an object's value, but it is typically some or all the data stored in the instance variables of the object. For example, the value of a object is based on the characters of the string; the method overrides the method to return `true` for any two string instances that contain the same characters in the same order. - -The following example shows how to override the method to test for value equality. It overrides the method for the `Person` class. If `Person` accepted its base class implementation of equality, two `Person` objects would be equal only if they referenced a single object. However, in this case, two `Person` objects are equal if they have the same value for the `Person.Id` property. - -:::code language="csharp" source="./snippets/System/Object/Equals/csharp/equalsoverride.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equalsoverride.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System/Object/Equals/vb/equalsoverride.vb" id="Snippet6"::: - -In addition to overriding , you can implement the interface to provide a strongly typed test for equality. - -The following statements must be true for all implementations of the method. In the list, `x`, `y`, and `z` represent object references that are not **null**. - -- `x.Equals(x)` returns `true`. - -- `x.Equals(y)` returns the same value as `y.Equals(x)`. - -- `x.Equals(y)` returns `true` if both `x` and `y` are `NaN`. - -- If `(x.Equals(y) && y.Equals(z))` returns `true`, then `x.Equals(z)` returns `true`. - -- Successive calls to `x.Equals(y)` return the same value as long as the objects referenced by `x` and `y` are not modified. - -- `x.Equals(null)` returns `false`. - -Implementations of must not throw exceptions; they should always return a value. For example, if `obj` is `null`, the method should return `false` instead of throwing an . - -Follow these guidelines when overriding : - -- Types that implement must override . - -- Types that override must also override ; otherwise, hash tables might not work correctly. - -- You should consider implementing the interface to support strongly typed tests for equality. Your implementation should return results that are consistent with . - -- If your programming language supports operator overloading and you overload the equality operator for a given type, you must also override the method to return the same result as the equality operator. This helps ensure that class library code that uses (such as and ) behaves in a manner that is consistent with the way the equality operator is used by application code. - -### Guidelines for reference types - -The following guidelines apply to overriding for a reference type: - -- Consider overriding if the semantics of the type are based on the fact that the type represents some value(s). - -- Most reference types must not overload the equality operator, even if they override . However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you must override the equality operator. - -- You should not override on a mutable reference type. This is because overriding requires that you also override the method, as discussed in the previous section. This means that the hash code of an instance of a mutable reference type can change during its lifetime, which can cause the object to be lost in a hash table. - -### Guidelines for value types - -The following guidelines apply to overriding for a value type: - -- If you are defining a value type that includes one or more fields whose values are reference types, you should override . The implementation provided by performs a byte-by-byte comparison for value types whose fields are all value types, but it uses reflection to perform a field-by-field comparison of value types whose fields include reference types. - -- If you override and your development language supports operator overloading, you must overload the equality operator. - -- You should implement the interface. Calling the strongly typed method avoids boxing the `obj` argument. - -## Examples - -The following example shows a `Point` class that overrides the method to provide value equality, and a `Point3D` class that is derived from `Point`. Because `Point` overrides to test for value equality, the method is not called. However, `Point3D.Equals` calls `Point.Equals` because `Point` implements in a manner that provides value equality. - -:::code language="csharp" source="./snippets/System/Object/Equals/csharp/equals2.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals2.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Object/Equals/vb/equals2.vb" id="Snippet1"::: - -The `Point.Equals` method checks to make sure that the `obj` argument is not **null** and that it references an instance of the same type as this object. If either check fails, the method returns `false`. - -The `Point.Equals` method calls the method to determine whether the runtime types of the two objects are identical. If the method used a check of the form `obj is Point` in C# or `TryCast(obj, Point)` in Visual Basic, the check would return `true` in cases where `obj` is an instance of a derived class of `Point`, even though `obj` and the current instance are not of the same runtime type. Having verified that both objects are of the same type, the method casts `obj` to type `Point` and returns the result of comparing the instance fields of the two objects. - -In `Point3D.Equals`, the inherited `Point.Equals` method, which overrides , is invoked before anything else is done. Because `Point3D` is a sealed class (`NotInheritable` in Visual Basic), a check in the form `obj is Point` in C# or `TryCast(obj, Point)` in Visual Basic is adequate to ensure that `obj` is a `Point3D` object. If it is a `Point3D` object, it is cast to a `Point` object and passed to the base class implementation of . Only when the inherited `Point.Equals` method returns `true` does the method compare the `z` instance fields introduced in the derived class. - -The following example defines a `Rectangle` class that internally implements a rectangle as two `Point` objects. The `Rectangle` class also overrides to provide for value equality. - -:::code language="csharp" source="./snippets/System/Object/Equals/csharp/equals3.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals3.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Object/Equals/vb/equals3.vb" id="Snippet1"::: - -Some languages such as C# and Visual Basic support operator overloading. When a type overloads the equality operator, it must also override the method to provide the same functionality. This is typically accomplished by writing the method in terms of the overloaded equality operator, as in the following example. - -:::code language="csharp" source="./snippets/System/Object/Equals/csharp/equals4.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Object/Equals/fsharp/equals4.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Object/Equals/vb/equals4.vb" id="Snippet1"::: - -Because `Complex` is a value type, it cannot be derived from. Therefore, the override to method need not call to determine the precise runtime type of each object, but can instead use the `is` operator in C# or the `TypeOf` operator in Visual Basic to check the type of the `obj` parameter. diff --git a/docs/fundamentals/runtime-libraries/system-object-finalize.md b/docs/fundamentals/runtime-libraries/system-object-finalize.md deleted file mode 100644 index c3f3d7dad0fe4..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-object-finalize.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: System.Object.Finalize method -description: Learn about the System.Object.Finalize method. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Object.Finalize method - -[!INCLUDE [context](includes/context.md)] - -The method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed. The method is protected and therefore is accessible only through this class or through a derived class. - -## How finalization works - -The class provides no implementation for the method, and the garbage collector does not mark types derived from for finalization unless they override the method. - -If a type does override the method, the garbage collector adds an entry for each instance of the type to an internal structure called the finalization queue. The finalization queue contains entries for all the objects in the managed heap whose finalization code must run before the garbage collector can reclaim their memory. The garbage collector then calls the method automatically under the following conditions: - -- After the garbage collector has discovered that an object is inaccessible, unless the object has been exempted from finalization by a call to the method. -- **On .NET Framework only**, during shutdown of an application domain, unless the object is exempt from finalization. During shutdown, even objects that are still accessible are finalized. - - is automatically called only once on a given instance, unless the object is re-registered by using a mechanism such as and the method has not been subsequently called. - - operations have the following limitations: - -- The exact time when the finalizer executes is undefined. To ensure deterministic release of resources for instances of your class, implement a `Close` method or provide a implementation. -- The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already been finalized when the finalizer of Object A starts. -- The thread on which the finalizer runs is unspecified. - -The method might not run to completion or might not run at all under the following exceptional circumstances: - -- If another finalizer blocks indefinitely (goes into an infinite loop, tries to obtain a lock it can never obtain, and so on). Because the runtime tries to run finalizers to completion, other finalizers might not be called if a finalizer blocks indefinitely. -- If the process terminates without giving the runtime a chance to clean up. In this case, the runtime's first notification of process termination is a DLL_PROCESS_DETACH notification. - -The runtime continues to finalize objects during shutdown only while the number of finalizable objects continues to decrease. - -If or an override of throws an exception, and the runtime is not hosted by an application that overrides the default policy, the runtime terminates the process and no active `try`/`finally` blocks or finalizers are executed. This behavior ensures process integrity if the finalizer cannot free or destroy resources. - -## Overriding the Finalize method - -You should override for a class that uses unmanaged resources, such as file handles or database connections that must be released when the managed object that uses them is discarded during garbage collection. You shouldn't implement a method for managed objects because the garbage collector releases managed resources automatically. - -> [!IMPORTANT] -> If a object is available that wraps your unmanaged resource, the recommended alternative is to implement the dispose pattern with a safe handle and not override . For more information, see [The SafeHandle alternative](#the-safehandle-alternative) section. - -The method does nothing by default, but you should override only if necessary, and only to release unmanaged resources. Reclaiming memory tends to take much longer if a finalization operation runs, because it requires at least two garbage collections. In addition, you should override the method for reference types only. The common language runtime only finalizes reference types. It ignores finalizers on value types. - -The scope of the method is `protected`. You should maintain this limited scope when you override the method in your class. By keeping a method protected, you prevent users of your application from calling an object's method directly. - -Every implementation of in a derived type must call its base type's implementation of . This is the only case in which application code is allowed to call . An object's method shouldn't call a method on any objects other than that of its base class. This is because the other objects being called could be collected at the same time as the calling object, such as in the case of a common language runtime shutdown. - -> [!NOTE] -> The C# compiler does not allow you to override the method. Instead, you provide a finalizer by implementing a [destructor](/dotnet/csharp/programming-guide/classes-and-structs/destructors) for your class. A C# destructor automatically calls the destructor of its base class. -> -> Visual C++ also provides its own syntax for implementing the method. For more information, see the "Destructors and finalizers" section of [How to: Define and Consume Classes and Structs (C++/CLI)](/cpp/dotnet/how-to-define-and-consume-classes-and-structs-cpp-cli). - -Because garbage collection is non-deterministic, you do not know precisely when the garbage collector performs finalization. To release resources immediately, you can also choose to implement the [dispose pattern](../../standard/garbage-collection/implementing-dispose.md) -and the interface. The implementation can be called by consumers of your class to free unmanaged resources, and you can use the method to free unmanaged resources in the event that the method is not called. - - can take almost any action, including resurrecting an object (that is, making the object accessible again) after it has been cleaned up during garbage collection. However, the object can only be resurrected once; cannot be called on resurrected objects during garbage collection. - -## The SafeHandle alternative - -Creating reliable finalizers is often difficult, because you cannot make assumptions about the state of your application, and because unhandled system exceptions such as and terminate the finalizer. Instead of implementing a finalizer for your class to release unmanaged resources, you can use an object that is derived from the class to wrap your unmanaged resources, and then implement the dispose pattern without a finalizer. The .NET Framework provides the following classes in the namespace that are derived from : - -- is a wrapper class for a file handle. -- is a wrapper class for memory-mapped file handles. -- is a wrapper class for a pointer to a block of unmanaged memory. -- , , and are wrapper classes for cryptographic handles. -- is a wrapper class for pipe handles. -- is a wrapper class for a handle to a registry key. -- is a wrapper class for a wait handle. - -The following example uses the [dispose pattern](../../standard/garbage-collection/implementing-dispose.md) with safe handles instead of overriding the method. It defines a `FileAssociation` class that wraps registry information about the application that handles files with a particular file extension. The two registry handles returned as `out` parameters by Windows [RegOpenKeyEx](/windows/win32/api/winreg/nf-winreg-regopenkeyexa) function calls are passed to the constructor. The type's protected `Dispose` method then calls the `SafeRegistryHandle.Dispose` method to free these two handles. - -:::code language="csharp" source="./snippets/System/Object/Finalize/csharp/finalize_safe.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Object/Finalize/fsharp/finalize_safe.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Object/Finalize/vb/finalize_safe.vb" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-object-gethashcode.md b/docs/fundamentals/runtime-libraries/system-object-gethashcode.md deleted file mode 100644 index 7f15850440dd5..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-object-gethashcode.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: System.Object.GetHashCode method -description: Learn about the System.Object.GetHashCode method. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Object.GetHashCode method - -[!INCLUDE [context](includes/context.md)] - -The method provides a hash code for algorithms that need quick checks of object equality. A hash code is a numeric value that is used to insert and identify an object in a hash-based collection, such as the class, the class, or a type derived from the class. - -> [!NOTE] -> For information about how hash codes are used in hash tables and for some additional hash code algorithms, see the [Hash Function](https://en.wikipedia.org/wiki/Hash_function) entry in Wikipedia. - -Two objects that are equal return hash codes that are equal. However, the reverse is not true: equal hash codes do not imply object equality, because different (unequal) objects can have identical hash codes. Furthermore, .NET does not guarantee the default implementation of the method, and the value this method returns may differ between .NET implementations, such as different versions of .NET Framework and .NET Core, and platforms, such as 32-bit and 64-bit platforms. For these reasons, do not use the default implementation of this method as a unique object identifier for hashing purposes. Two consequences follow from this: - -- You should not assume that equal hash codes imply object equality. -- You should never persist or use a hash code outside the application domain in which it was created, because the same object may hash across application domains, processes, and platforms. - -> [!WARNING] -> A hash code is intended for efficient insertion and lookup in collections that are based on a hash table. A hash code is not a permanent value. For this reason: -> -> - Do not serialize hash code values or store them in databases. -> - Do not use the hash code as the key to retrieve an object from a keyed collection. -> - Do not send hash codes across application domains or processes. In some cases, hash codes may be computed on a per-process or per-application domain basis. -> - Do not use the hash code instead of a value returned by a cryptographic hashing function if you need a cryptographically strong hash. For cryptographic hashes, use a class derived from the or class. -> - Do not test for equality of hash codes to determine whether two objects are equal. (Unequal objects can have identical hash codes.) To test for equality, call the or method. - -The method can be overridden by a derived type. If is not overridden, hash codes for reference types are computed by calling the method of the base class, which computes a hash code based on an object's reference; for more information, see . In other words, two objects for which the method returns `true` have identical hash codes. If value types do not override , the method of the base class uses reflection to compute the hash code based on the values of the type's fields. In other words, value types whose fields have equal values have equal hash codes. For more information about overriding , see the "Notes to Inheritors" section. - -> [!WARNING] -> If you override the method, you should also override , and vice versa. If your overridden method returns `true` when two objects are tested for equality, your overridden method must return the same value for the two objects. - -If an object that is used as a key in a hash table does not provide a useful implementation of , you can specify a hash code provider by supplying an implementation to one of the overloads of the class constructor. - -## Notes for the Windows Runtime - -When you call the method on a class in the Windows Runtime, it provides the default behavior for classes that don't override . This is part of the support that .NET provides for the Windows Runtime (see [.NET Support for Windows Store Apps and Windows Runtime](/dotnet/standard/cross-platform/support-for-windows-store-apps-and-windows-runtime)). Classes in the Windows Runtime don't inherit , and currently don't implement a . However, they appear to have , , and methods when you use them in your C# or Visual Basic code, and the .NET Framework provides the default behavior for these methods. - -> [!NOTE] -> Windows Runtime classes that are written in C# or Visual Basic can override the method. - -## Examples - -One of the simplest ways to compute a hash code for a numeric value that has the same or a smaller range than the type is to simply return that value. The following example shows such an implementation for a `Number` structure. - -:::code language="csharp" source="./snippets/System/Object/GetHashCode/csharp/direct1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Object/GetHashCode/fsharp/direct1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Object/GetHashCode/vb/direct1.vb" id="Snippet1"::: - -Frequently, a type has multiple data fields that can participate in generating the hash code. One way to generate a hash code is to combine these fields using an `XOR (eXclusive OR)` operation, as shown in the following example. - -:::code language="csharp" source="./snippets/System/Object/GetHashCode/csharp/xor1.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Object/GetHashCode/fsharp/xor1.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Object/GetHashCode/vb/xor1.vb" id="Snippet2"::: - -The previous example returns the same hash code for (n1, n2) and (n2, n1), and so it might generate more collisions than are desirable. On .NET 5+, the recommended solution is to use . It avoids the symmetry problem and produces a well-distributed hash code without the overhead of creating a `Tuple` object. - -:::code language="csharp" source="./snippets/System/Object/GetHashCode/csharp/xor2.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/Object/GetHashCode/fsharp/xor2.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/Object/GetHashCode/vb/xor2.vb" id="Snippet3"::: - -In .NET Framework, an alternative is to weight the individual hash codes by left-shifting the hash codes of successive fields by two or more bits. Optimally, bits shifted beyond bit 31 should wrap around rather than be discarded. Since bits are discarded by the left-shift operators in both C# and Visual Basic, this requires creating a left shift-and-wrap method like the following: - -:::code language="csharp" source="./snippets/System/Object/GetHashCode/csharp/shift1.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/Object/GetHashCode/fsharp/shift1.fs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/Object/GetHashCode/vb/shift1.vb" id="Snippet4"::: - -The following example then uses this shift-and-wrap method to compute the hash code of the `Point` structure used in the previous examples. - -:::code language="csharp" source="./snippets/System/Object/GetHashCode/csharp/shift1.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/Object/GetHashCode/fsharp/shift1.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/Object/GetHashCode/vb/shift1.vb" id="Snippet5"::: diff --git a/docs/fundamentals/runtime-libraries/system-object-tostring.md b/docs/fundamentals/runtime-libraries/system-object-tostring.md deleted file mode 100644 index 2eea195877c6e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-object-tostring.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: System.Object.ToString method -description: Learn about the System.Object.ToString method. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Object.ToString method - -[!INCLUDE [context](includes/context.md)] - - is a common formatting method in .NET. It converts an object to its string representation so that it is suitable for display. (For information about formatting support in .NET, see [Formatting Types](../../standard/base-types/formatting-types.md).) Default implementations of the method return the fully qualified name of the object's type. - -> [!IMPORTANT] -> You may have reached this page by following the link from the member list of another type. That is because that type does not override . Instead, it inherits the functionality of the method. - -Types frequently override the method to provide a more suitable string representation of a particular type. Types also frequently overload the method to provide support for format strings or culture-sensitive formatting. - -## The default Object.ToString() method - -The default implementation of the method returns the fully qualified name of the type of the , as the following example shows. - -:::code language="csharp" source="./snippets/System/Object/ToString/csharp/tostring1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/tostring1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Object/ToString/vb/tostring1.vb" id="Snippet1"::: - -Because is the base class of all reference types in .NET, this behavior is inherited by reference types that do not override the method. The following example illustrates this. It defines a class named `Object1` that accepts the default implementation of all members. Its method returns the object's fully qualified type name. - -:::code language="csharp" source="./snippets/System/Object/ToString/csharp/tostring2.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/tostring2.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Object/ToString/vb/tostring2.vb" id="Snippet2"::: - -## Override the Object.ToString() method - -Types commonly override the method to return a string that represents the object instance. For example, the base types such as , , and provide implementations that return the string form of the value that the object represents. The following example defines a class, `Object2`, that overrides the method to return the type name along with its value. - -:::code language="csharp" source="./snippets/System/Object/ToString/csharp/tostring3.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/tostring3.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/Object/ToString/vb/tostring3.vb" id="Snippet3"::: - -The following table lists the type categories in .NET and indicates whether or not they override the method. - -| Type category | Overrides Object.ToString() | Behavior | -|---------------|-----------------------------|----------| -| Class | n/a | n/a | -| Structure | Yes () | Same as `Object.ToString()` | -| Enumeration | Yes () | The member name | -| Interface | No| n/a | -| Delegate | No| n/a | - -See the Notes to Inheritors section for additional information on overriding . - -## Overload the ToString method - -In addition to overriding the parameterless method, many types overload the `ToString` method to provide versions of the method that accept parameters. Most commonly, this is done to provide support for variable formatting and culture-sensitive formatting. - -The following example overloads the `ToString` method to return a result string that includes the value of various fields of an `Automobile` class. It defines four format strings: G, which returns the model name and year; D, which returns the model name, year, and number of doors; C, which returns the model name, year, and number of cylinders; and A, which returns a string with all four field values. - -:::code language="csharp" source="./snippets/System/Object/ToString/csharp/tostringoverload1.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/tostringoverload1.fs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/Object/ToString/vb/tostringoverload1.vb" id="Snippet4"::: - -The following example calls the overloaded method to display culture-sensitive formatting of a currency value. - -:::code language="csharp" source="./snippets/System/Object/ToString/csharp/tostringoverload2.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/tostringoverload2.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/Object/ToString/vb/tostringoverload2.vb" id="Snippet5"::: - -For more information on format strings and culture-sensitive formatting, see [Formatting Types](../../standard/base-types/formatting-types.md). For the format strings supported by numeric values, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md). For the format strings supported by date and time values, see [Standard Date and Time Format Strings](../../standard/base-types/standard-date-and-time-format-strings.md) and [Custom Date and Time Format Strings](../../standard/base-types/custom-date-and-time-format-strings.md). - -## Extend the Object.ToString method - -Because a type inherits the default method, you may find its behavior undesirable and want to change it. This is particularly true of arrays and collection classes. While you may expect the `ToString` method of an array or collection class to display the values of its members, it instead displays the type fully qualified type name, as the following example shows. - -:::code language="csharp" source="./snippets/System/Object/ToString/csharp/array1.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/array1.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System/Object/ToString/vb/array1.vb" id="Snippet6"::: - -You have several options to produce the result string that you'd like. - -- If the type is an array, a collection object, or an object that implements the or interfaces, you can enumerate its elements by using the `foreach` statement in C# or the `For Each...Next` construct in Visual Basic. - -- If the class is not `sealed` (in C#) or `NotInheritable` (in Visual Basic), you can develop a wrapper class that inherits from the base class whose method you want to customize. At a minimum, this requires that you do the following: - - 1. Implement any necessary constructors. Derived classes do not inherit their base class constructors. - 2. Override the method to return the result string that you'd like. - - The following example defines a wrapper class for the class. It overrides the method to display the value of each method of the collection rather than the fully qualified type name. - - :::code language="csharp" source="./snippets/System/Object/ToString/csharp/customize1.cs" id="Snippet7"::: - :::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/customize1.fs" id="Snippet7"::: - :::code language="vb" source="./snippets/System/Object/ToString/vb/customize1.vb" id="Snippet7"::: - -- Develop an [extension method](../../standard/design-guidelines/extension-methods.md) that returns the result string that you want. Note that you can't override the default method in this way—that is, your extension class (in C#) or module (in Visual Basic) cannot have a parameterless method named `ToString` that's called in place of the original type's `ToString` method. You'll have to provide some other name for your parameterless `ToString` replacement. - - The following example defines two methods that extend the class: a parameterless `ToString2` method, and a `ToString` method with a parameter that represents a format string. - - :::code language="csharp" source="./snippets/System/Object/ToString/csharp/customize2.cs" id="Snippet8"::: - :::code language="fsharp" source="./snippets/System/Object/ToString/fsharp/customize2.fs" id="Snippet8"::: - :::code language="vb" source="./snippets/System/Object/ToString/vb/customize2.vb" id="Snippet8"::: - -## Notes for the Windows Runtime - -When you call the method on a class in the Windows Runtime, it provides the default behavior for classes that don't override . This is part of the support that .NET provides for the Windows Runtime (see [.NET Support for Windows Store Apps and Windows Runtime](/dotnet/standard/cross-platform/support-for-windows-store-apps-and-windows-runtime)). Classes in the Windows Runtime don't inherit , and don't always implement a . However, they always appear to have , , and methods when you use them in your C# or Visual Basic code, and .NET provides a default behavior for these methods. - -The common language runtime uses [IStringable.ToString](xref:Windows.Foundation.IStringable.ToString) on a Windows Runtime object before falling back to the default implementation of . - -> [!NOTE] -> Windows Runtime classes that are written in C# or Visual Basic can override the method. - -### The Windows Runtime and the IStringable Interface - -The Windows Runtime includes an [IStringable](xref:Windows.Foundation.IStringable) interface whose single method, [IStringable.ToString](xref:Windows.Foundation.IStringable.ToString), provides basic formatting support comparable to that provided by . To prevent ambiguity, you should not implement [IStringable](xref:Windows.Foundation.IStringable) on managed types. - -When managed objects are called by native code or by code written in languages such as JavaScript or C++/CX, they appear to implement [IStringable](xref:Windows.Foundation.IStringable). The common language runtime automatically routes calls from [IStringable.ToString](xref:Windows.Foundation.IStringable.ToString) to if [IStringable](xref:Windows.Foundation.IStringable) is not implemented on the managed object. - -> [!WARNING] -> Because the common language runtime auto-implements [IStringable](xref:Windows.Foundation.IStringable) for all managed types in Windows Store apps, we recommend that you do not provide your own `IStringable` implementation. Implementing `IStringable` may result in unintended behavior when calling `ToString` from the Windows Runtime, C++/CX, or JavaScript. - -If you do choose to implement [IStringable](xref:Windows.Foundation.IStringable) in a public managed type that's exported in a Windows Runtime component, the following restrictions apply: - -- You can define the [IStringable](xref:Windows.Foundation.IStringable) interface only in a "class implements" relationship, as follows: - - ```csharp - public class NewClass : IStringable - ``` - - ```vb - Public Class NewClass : Implements IStringable - ``` - -- You cannot implement [IStringable](xref:Windows.Foundation.IStringable) on an interface. - -- You cannot declare a parameter to be of type [IStringable](xref:Windows.Foundation.IStringable). - -- [IStringable](xref:Windows.Foundation.IStringable) cannot be the return type of a method, property, or field. - -- You cannot hide your [IStringable](xref:Windows.Foundation.IStringable) implementation from base classes by using a method definition such as the following: - - ```csharp - public class NewClass : IStringable - { - public new string ToString() - { - return "New ToString in NewClass"; - } - } - ``` - - Instead, the [IStringable.ToString](xref:Windows.Foundation.IStringable.ToString) implementation must always override the base class implementation. You can hide a `ToString` implementation only by invoking it on a strongly typed class instance. - -Under a variety of conditions, calls from native code to a managed type that implements [IStringable](xref:Windows.Foundation.IStringable) or hides its [ToString](xref:Windows.Foundation.IStringable.ToString) implementation can produce unexpected behavior. diff --git a/docs/fundamentals/runtime-libraries/system-object.md b/docs/fundamentals/runtime-libraries/system-object.md deleted file mode 100644 index 37c063ebb20f7..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-object.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: System.Object class -description: Learn about the System.Object class. -ms.date: 12/31/2023 ---- -# System.Object class - -[!INCLUDE [context](includes/context.md)] - -The class is the ultimate base class of all .NET classes; it is the root of the type hierarchy. - -Because all classes in .NET are derived from , every method defined in the class is available in all objects in the system. Derived classes can and do override some of these methods, including: - -- : Supports comparisons between objects. -- : Performs cleanup operations before an object is automatically reclaimed. -- : Generates a number corresponding to the value of the object to support the use of a hash table. -- : Manufactures a human-readable text string that describes an instance of the class. - -Languages typically don't require a class to declare inheritance from because the inheritance is implicit. - -## Performance considerations - -If you're designing a class, such as a collection, that must handle any type of object, you can create class members that accept instances of the class. However, the process of boxing and unboxing a type carries a performance cost. If you know your new class will frequently handle certain value types you can use one of two tactics to minimize the cost of boxing. - -- Create a general method that accepts an type, and a set of type-specific method overloads that accept each value type you expect your class to frequently handle. If a type-specific method exists that accepts the calling parameter type, no boxing occurs and the type-specific method is invoked. If there is no method argument that matches the calling parameter type, the parameter is boxed and the general method is invoked. -- Design your type and its members to use [generics](../../standard/generics.md). The common language runtime creates a closed generic type when you create an instance of your class and specify a generic type argument. The generic method is type-specific and can be invoked without boxing the calling parameter. - -Although it's sometimes necessary to develop general purpose classes that accept and return types, you can improve performance by also providing a type-specific class to handle a frequently used type. For example, providing a class that is specific to setting and getting Boolean values eliminates the cost of boxing and unboxing Boolean values. diff --git a/docs/fundamentals/runtime-libraries/system-random.md b/docs/fundamentals/runtime-libraries/system-random.md deleted file mode 100644 index 6085b1e17d177..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-random.md +++ /dev/null @@ -1,242 +0,0 @@ ---- -title: System.Random class -description: Learn about the System.Random class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Random class - -[!INCLUDE [context](includes/context.md)] - -The class represents a pseudo-random number generator, which is an algorithm that produces a sequence of numbers that meet certain statistical requirements for randomness. - -Pseudo-random numbers are chosen with equal probability from a finite set of numbers. The chosen numbers are not completely random because a mathematical algorithm is used to select them, but they are sufficiently random for practical purposes. The implementation of the class is based on a modified version of Donald E. Knuth's subtractive random number generator algorithm. For more information, see D. E. Knuth. *The Art of Computer Programming, Volume 2: Seminumerical Algorithms*. Addison-Wesley, Reading, MA, third edition, 1997. - -To generate a cryptographically secure random number, such as one that's suitable for creating a random password, use one of the static methods in the class. - -## Instantiate the random number generator - -You instantiate the random number generator by providing a seed value (a starting value for the pseudo-random number generation algorithm) to a class constructor. You can supply the seed value either explicitly or implicitly: - -- The constructor uses an explicit seed value that you supply. -- The constructor uses the default seed value. This is the most common way of instantiating the random number generator. - -In .NET Framework, the default seed value is time-dependent. In .NET Core, the default seed value is produced by the thread-static, pseudo-random number generator. - -If the same seed is used for separate objects, they will generate the same series of random numbers. This can be useful for creating a test suite that processes random values, or for replaying games that derive their data from random numbers. However, note that objects in processes running under different versions of .NET Framework might return differentseries of random numbers even if they're instantiated with identical seed values. - -To produce different sequences of random numbers, you can make the seed value time-dependent, thereby producing a different series with each new instance of . The parameterized constructor can take an value based on the number of ticks in the current time, whereas the parameterless constructor uses the system clock to generate its seed value. However, on .NET Framework only, because the clock has finite resolution, using the parameterless constructor to create different objects in close succession creates random number generators that produce identical sequences of random numbers. The following example illustrates how two objects that are instantiated in close succession in a .NET Framework application generate an identical series of random numbers. On most Windows systems, objects created within 15 milliseconds of one another are likely to have identical seed values. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/Random1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/Random1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/Random1.vb" id="Snippet1"::: - -To avoid this problem, create a single object instead of multiple objects. Note that the `Random` class in .NET Core does not have this limitation. - -## Avoid multiple instantiations - -On .NET Framework, initializing two random number generators in a tight loop or in rapid succession creates two random number generators that can produce identical sequences of random numbers. In most cases, this is not the developer's intent and can lead to performance issues, because instantiating and initializing a random number generator is a relatively expensive process. - -Both to improve performance and to avoid inadvertently creating separate random number generators that generate identical numeric sequences, we recommend that you create one object to generate many random numbers over time, instead of creating new objects to generate one random number. - -However, the class isn't thread safe. If you call methods from multiple threads, follow the guidelines discussed in the next section. - -## Thread safety - -Instead of instantiating individual objects, we recommend that you create a single instance to generate all the random numbers needed by your app. However, objects are not thread safe. If your app calls methods from multiple threads, you must use a synchronization object to ensure that only one thread can access the random number generator at a time. If you don't ensure that the object is accessed in a thread-safe way, calls to methods that return random numbers return 0. - -The following example uses the C# [lock Statement](/dotnet/csharp/language-reference/keywords/lock-statement), the F# [lock function](https://fsharp.github.io/fsharp-core-docs/reference/fsharp-core-operators.html#lock) and the Visual Basic [SyncLock statement](../../visual-basic/language-reference/statements/synclock-statement.md) to ensure that a single random number generator is accessed by 11 threads in a thread-safe manner. Each thread generates 2 million random numbers, counts the number of random numbers generated and calculates their sum, and then updates the totals for all threads when it finishes executing. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/threadsafeex1.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/threadsafeex1.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/threadsafeex1.vb" id="Snippet3"::: - -The example ensures thread-safety in the following ways: - -- The attribute is used to define thread-local variables that track the total number of random numbers generated and their sum for each thread. -- A lock (the `lock` statement in C#, the `lock` function in F# and the `SyncLock` statement in Visual Basic) protects access to the variables for the total count and sum of all random numbers generated on all threads. -- A semaphore (the object) is used to ensure that the main thread blocks until all other threads complete execution. -- The example checks whether the random number generator has become corrupted by determining whether two consecutive calls to random number generation methods return 0. If corruption is detected, the example uses the object to signal that all threads should be canceled. -- Before generating each random number, each thread checks the state of the object. If cancellation is requested, the example calls the method to cancel the thread. - -The following example is identical to the first, except that it uses a object and a lambda expression instead of objects. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/threadsafeex2.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/threadsafeex2.fs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/threadsafeex2.vb" id="Snippet4"::: - -It differs from the first example in the following ways: - -- The variables to keep track of the number of random numbers generated and their sum in each task are local to the task, so there is no need to use the attribute. -- The static method is used to ensure that the main thread doesn't complete before all tasks have finished. There is no need for the object. -- The exception that results from task cancellation is surfaced in the method. In the previous example, it is handled by each thread. - -## Generate different types of random numbers - -The random number generator provides methods that let you generate the following kinds of random numbers: - -- A series of values. You determine the number of byte values by passing an array initialized to the number of elements you want the method to return to the method. The following example generates 20 bytes. - - :::code language="csharp" source="./snippets/System/Random/Overview/csharp/nextbytes1.cs" id="Snippet5"::: - :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/nextbytes1.fs" id="Snippet5"::: - :::code language="vb" source="./snippets/System/Random/Overview/vb/nextbytes1.vb" id="Snippet5"::: - -- A single integer. You can choose whether you want an integer from 0 to a maximum value ( - 1) by calling the method, an integer between 0 and a specific value by calling the method, or an integer within a range of values by calling the method. In the parameterized overloads, the specified maximum value is exclusive; that is, the actual maximum number generated is one less than the specified value. - - The following example calls the method to generate 10 random numbers between -10 and 10. Note that the second argument to the method specifies the exclusive upper bound of the range of random values returned by the method. In other words, the largest integer that the method can return is one less than this value. - - :::code language="csharp" source="./snippets/System/Random/Overview/csharp/nextex1.cs" id="Snippet6"::: - :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/nextex1.fs" id="Snippet6"::: - :::code language="vb" source="./snippets/System/Random/Overview/vb/nextex1.vb" id="Snippet6"::: - -- A single floating-point value from 0.0 to less than 1.0 by calling the method. The exclusive upper bound of the random number returned by the method is 1, so its actual upper bound is 0.99999999999999978. The following example generates 10 random floating-point numbers. - - :::code language="csharp" source="./snippets/System/Random/Overview/csharp/nextdoubleex1.cs" id="Snippet7"::: - :::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/nextdoubleex1.fs" id="Snippet7"::: - :::code language="vb" source="./snippets/System/Random/Overview/vb/nextdoubleex1.vb" id="Snippet7"::: - -> [!IMPORTANT] -> The method allows you to specify the range of the returned random number. However, the `maxValue` parameter, which specifies the upper range returned number, is an exclusive, not an inclusive, value. This means that the method call `Next(0, 100)` returns a value between 0 and 99, and not between 0 and 100. - -You can also use the class for such tasks as generating [random Boolean values](#generate-random-boolean-values), generating [random floating-point values in a specified range](#retrieve-floating-point-values-in-a-specified-range), generating [Generate random 64-bit integers](#generate-random-64-bit-integers), and [retrieving a unique element from an array or collection](#retrieve-a-unique-element-from-an-array-or-collection). - -## Substitute your own algorithm - -You can implement your own random number generator by inheriting from the class and supplying your random number generation algorithm. To supply your own algorithm, you must override the method, which implements the random number generation algorithm. You should also override the , , and methods to ensure that they call your overridden method. You don't have to override the and methods. - -For an example that derives from the class and modifies its default pseudo-random number generator, see the reference page. - -## Retrieve the same sequence of random values - -Sometimes you want to generate the same sequence of random numbers in software test scenarios and in game playing. Testing with the same sequence of random numbers allows you to detect regressions and confirm bug fixes. Using the same sequence of random number in games allows you to replay previous games. - -You can generate the same sequence of random numbers by providing the same seed value to the constructor. The seed value provides a starting value for the pseudo-random number generation algorithm. The following example uses 100100 as an arbitrary seed value to instantiate the object, displays 20 random floating-point values, and persists the seed value. It then restores the seed value, instantiates a new random number generator, and displays the same 20 random floating-point values. Note that the example may produce different sequences of random numbers if run on different versions of .NET. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/same1.cs" id="Snippet12"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/same1.fs" id="Snippet12"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/same1.vb" id="Snippet12"::: - -## Retrieve unique sequences of random numbers - -Providing different seed values to instances of the class causes each random number generator to produce a different sequence of values. You can provide a seed value either explicitly by calling the constructor, or implicitly by calling the constructor. Most developers call the parameterless constructor, which uses the system clock. The following example uses this approach to instantiate two instances. Each instance displays a series of 10 random integers. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/unique.cs" id="Snippet13"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/unique.fs" id="Snippet13"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/unique.vb" id="Snippet13"::: - -However, because of its finite resolution, the system clock doesn't detect time differences that are less than approximately 15 milliseconds. Therefore, if your code calls the overload on .NET Framework to instantiate two objects in succession, you might inadvertently be providing the objects with identical seed values. (The class in .NET Core does not have this limitation.) To see this in the previous example, comment out the method call, and compile and run the example again. - -To prevent this from happening, we recommend that you instantiate a single object rather than multiple ones. However, since isn't thread safe, you must use some synchronization device if you access a instance from multiple threads; for more information, see the [Thread safety](#thread-safety) section. Alternately, you can use a delay mechanism, such as the method used in the previous example, to ensure that the instantiations occur more than 15 millisecond apart. - -## Retrieve integers in a specified range - -You can retrieve integers in a specified range by calling the method, which lets you specify both the lower and the upper bound of the numbers you'd like the random number generator to return. The upper bound is an exclusive, not an inclusive, value. That is, it isn't included in the range of values returned by the method. The following example uses this method to generate random integers between -10 and 10. Note that it specifies 11, which is one greater than the desired value, as the value of the `maxValue` argument in the method call. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/range1.cs" id="Snippet15"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/range1.fs" id="Snippet15"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/range1.vb" id="Snippet15"::: - -## Retrieve integers with a specified number of digits - -You can call the method to retrieve numbers with a specified number of digits. For example, to retrieve numbers with four digits (that is, numbers that range from 1000 to 9999), you call the method with a `minValue` value of 1000 and a `maxValue` value of 10000, as the following example shows. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/range2.cs" id="Snippet16"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/range2.fs" id="Snippet16"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/range2.vb" id="Snippet16"::: - -## Retrieve floating-point values in a specified range - -The method returns random floating-point values that range from 0 to less than 1. However, you'll often want to generate random values in some other range. - -If the interval between the minimum and maximum desired values is 1, you can add the difference between the desired starting interval and 0 to the number returned by the method. The following example does this to generate 10 random numbers between -1 and 0. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/doublerange2.cs" id="Snippet17"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/doublerange2.fs" id="Snippet17"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/doublerange2.vb" id="Snippet17"::: - -To generate random floating-point numbers whose lower bound is 0 but upper bound is greater than 1 (or, in the case of negative numbers, whose lower bound is less than -1 and upper bound is 0), multiply the random number by the non-zero bound. The following example does this to generate 20 million random floating-point numbers that range from 0 to . In also displays the distribution of the random values generated by the method. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/doublerange1.cs" id="Snippet18"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/doublerange1.fs" id="Snippet18"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/doublerange1.vb" id="Snippet18"::: - -To generate random floating-point numbers between two arbitrary values, like the method does for integers, use the following formula: - -```csharp -Random.NextDouble() * (maxValue - minValue) + minValue -``` - -The following example generates 1 million random numbers that range from 10.0 to 11.0, and displays their distribution. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/doublerange3.cs" id="Snippet19"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/doublerange3.fs" id="Snippet19"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/doublerange3.vb" id="Snippet19"::: - -## Generate random Boolean values - -The class doesn't provide methods that generate values. However, you can define your own class or method to do that. The following example defines a class, `BooleanGenerator`, with a single method, `NextBoolean`. The `BooleanGenerator` class stores a object as a private variable. The `NextBoolean` method calls the method and passes the result to the method. Note that 2 is used as the argument to specify the upper bound of the random number. Since this is an exclusive value, the method call returns either 0 or 1. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/booleans1.cs" id="Snippet8"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/booleans1.fs" id="Snippet8"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/booleans1.vb" id="Snippet8"::: - -Instead of creating a separate class to generate random values, the example could simply have defined a single method. In that case, however, the object should have been defined as a class-level variable to avoid instantiating a new instance in each method call. In Visual Basic, the Random instance can be defined as a [Static](../../visual-basic/language-reference/modifiers/static.md) variable in the `NextBoolean` method. The following example provides an implementation. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/booleans2.cs" id="Snippet20"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/booleans2.fs" id="Snippet20"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/booleans2.vb" id="Snippet20"::: - -## Generate random 64-bit integers - -The overloads of the method return 32-bit integers. However, in some cases, you might want to work with 64-bit integers. You can do this as follows: - -1. Call the method to retrieve a double-precision floating point value. - -2. Multiply that value by . - -The following example uses this technique to generate 20 million random long integers and categorizes them in 10 equal groups. It then evaluates the distribution of the random numbers by counting the number in each group from 0 to . As the output from the example shows, the numbers are distributed more or less equally through the range of a long integer. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/long1.cs" id="Snippet14"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/long1.fs" id="Snippet14"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/long1.vb" id="Snippet14"::: - -An alternative technique that uses bit manipulation does not generate truly random numbers. This technique calls to generate two integers, left-shifts one by 32 bits, and ORs them together. This technique has two limitations: - -1. Because bit 31 is the sign bit, the value in bit 31 of the resulting long integer is always 0. This can be addressed by generating a random 0 or 1, left-shifting it 31 bits, and ORing it with the original random long integer. - -2. More seriously, because the probability that the value returned by will be 0, there will be few if any random numbers in the range 0x0-0x00000000FFFFFFFF. - -## Retrieve bytes in a specified range - -The overloads of the method allow you to specify the range of random numbers, but the method does not. The following example implements a `NextBytes` method that lets you specify the range of the returned bytes. It defines a `Random2` class that derives from and overloads its `NextBytes` method. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/bytes1.cs" id="Snippet9"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/bytes1.fs" id="Snippet9"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/bytes1.vb" id="Snippet9"::: - -The `NextBytes(Byte[], Byte, Byte)` method wraps a call to the method and specifies the minimum value and one greater than the maximum value (in this case, 0 and 101) that we want returned in the byte array. Because we are sure that the integer values returned by the method are within the range of the data type, we can safely cast them (in C# and F#) or convert them (in Visual Basic) from integers to bytes. - -## Retrieve an element from an array or collection at random - -Random numbers often serve as indexes to retrieve values from arrays or collections. To retrieve a random index value, you can call the method, and use the lower bound of the array as the value of its `minValue` argument and one greater than the upper bound of the array as the value of its `maxValue` argument. For a zero-based array, this is equivalent to its property, or one greater than the value returned by the method. The following example randomly retrieves the name of a city in the United States from an array of cities. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/array1.cs" id="Snippet10"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/array1.fs" id="Snippet10"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/array1.vb" id="Snippet10"::: - -## Retrieve a unique element from an array or collection - -A random number generator can always return duplicate values. As the range of numbers becomes smaller or the number of values generated becomes larger, the probability of duplicates grows. If random values must be unique, more numbers are generated to compensate for duplicates, resulting in increasingly poor performance. - -There are a number of techniques to handle this scenario. One common solution is to create an array or collection that contains the values to be retrieved, and a parallel array that contains random floating-point numbers. The second array is populated with random numbers at the time the first array is created, and the method is used to sort the first array by using the values in the parallel array. - -For example, if you're developing a Solitaire game, you want to ensure that each card is used only once. Instead of generating random numbers to retrieve a card and tracking whether that card has already been dealt, you can create a parallel array of random numbers that can be used to sort the deck. Once the deck is sorted, your app can maintain a pointer to indicate the index of the next card on the deck. - -The following example illustrates this approach. It defines a `Card` class that represents a playing card and a `Dealer` class that deals a deck of shuffled cards. The `Dealer` class constructor populates two arrays: a `deck` array that has class scope and that represents all the cards in the deck; and a local `order` array that has the same number of elements as the `deck` array and is populated with randomly generated values. The method is then called to sort the `deck` array based on the values in the `order` array. - -:::code language="csharp" source="./snippets/System/Random/Overview/csharp/uniquearray1.cs" id="Snippet11"::: -:::code language="fsharp" source="./snippets/System/Random/Overview/fsharp/uniquearray1.fs" id="Snippet11"::: -:::code language="vb" source="./snippets/System/Random/Overview/vb/uniquearray1.vb" id="Snippet11"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-context-customreflectioncontext.md b/docs/fundamentals/runtime-libraries/system-reflection-context-customreflectioncontext.md deleted file mode 100644 index a40f8a724451f..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-context-customreflectioncontext.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: System.Reflection.Context.CustomReflectionContext class -description: Learn about the System.Reflection.Context.CustomReflectionContext class. -ms.date: 02/12/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Context.CustomReflectionContext class - -[!INCLUDE [context](includes/context.md)] - - provides a way for you to add or remove custom attributes from reflection objects, or add dummy properties to those objects, without re-implementing the complete reflection model. The default simply wraps reflection objects without making any changes, but by subclassing and overriding the relevant methods, you can add, remove, or change the attributes that apply to any reflected parameter or member, or add new properties to a reflected type. - -For example, suppose that your code follows the convention of applying a particular attribute to factory methods, but you're now required to work with third-party code that lacks attributes. You can use to specify a rule for identifying the objects that should have attributes and to supply the objects with those attributes when they're viewed from your code. - -To use effectively, the code that uses the reflected objects must support the notion of specifying a reflection context, instead of assuming that all reflected objects are associated with the runtime reflection context. Many reflection methods in the .NET Framework provide a parameter for this purpose. - -To modify the attributes that are applied to a reflected parameter or member, override the or method. These methods take the reflected object and the list of attributes under its current reflection context, and return the list of attributes it should have under the custom reflection context. - -> [!WARNING] -> methods should not access the list of attributes of a reflected object or method directly by calling the method on the provided or instance, but should instead use the `declaredAttributes` list, which is passed as a parameter to the method overloads. - -To add properties to a reflected type, override the method. The method accepts a parameter that specifies the reflected type, and returns a list of additional properties. You should use the method to create property objects to return. You can specify delegates when creating the property that serve as the property accessor, and you can omit one of the accessors to create a read-only or write-only property. Note that such dummy properties have no metadata or Common Intermediate Language (CIL) backing. - -> [!WARNING] -> -> - Be cautious about equality among reflected objects when you work with reflection contexts, because objects might represent the same reflected object in multiple contexts. You can use the method to obtain a particular reflection context's version of a reflected object. -> - A object alters the attributes returned by a particular reflection object, such as those obtained by the method. It doesn't alter the custom attribute data returned by the method, and these two lists won't match when you use a custom reflection context. - -## Example - -The following example demonstrates how to subclass to add a custom attribute to all the members of a given type whose names begin with "To". To run this code, paste it into an empty console project and add a reference to the `System.Reflection.Context` NuGet package. - -:::code language="csharp" source="./snippets/system-reflection-context-customreflectioncontext/csharp/program.cs" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-assemblybuilder.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-assemblybuilder.md deleted file mode 100644 index bd00550854ce7..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-assemblybuilder.md +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: System.Reflection.Emit.AssemblyBuilder class -description: Learn about the System.Reflection.Emit.AssemblyBuilder class. -ms.date: 12/31/2023 ---- -# System.Reflection.Emit.AssemblyBuilder class - -[!INCLUDE [context](includes/context.md)] - -A dynamic assembly is an assembly that is created using the Reflection Emit APIs. A dynamic assembly can reference types defined in another dynamic or static assembly. You can use to generate dynamic assemblies in memory and execute their code during the same application run. In .NET 9 we added a new [PersistedAssemblyBuilder](system-reflection-emit-persistedassemblybuilder.md) with fully managed implementation of reflection emit that allows you save the assembly into a file. In .NET Framework, you can do both—run the dynamic assembly and save it to a file. The dynamic assembly created for saving is called a *persisted* assembly, while the regular memory-only assembly is called *transient* or *runnable*. In .NET Framework, a dynamic assembly can consist of one or more dynamic modules. In .NET Core and .NET 5+, a dynamic assembly can only consist of one dynamic module. - -The way you create an instance differs for each implementation, but further steps for defining a module, type, method, or enum, and for writing IL, are quite similar. - -## Runnable dynamic assemblies in .NET - -To get a runnable object, use the method. -Dynamic assemblies can be created using one of the following access modes: - -- - - The dynamic assembly represented by an can be used to execute the emitted code. - -- - - The dynamic assembly represented by an can be used to execute the emitted code and is automatically reclaimed by garbage collector. - -The access mode must be specified by providing the appropriate value in the call to the method when the dynamic assembly is defined and cannot be changed later. The runtime uses the access mode of a dynamic assembly to optimize the assembly's internal representation. - -The following example demonstrates how to create and run an assembly: - -```csharp -public void CreateAndRunAssembly(string assemblyPath) -{ - AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("MyAssembly"), AssemblyBuilderAccess.Run); - ModuleBuilder mob = ab.DefineDynamicModule("MyModule"); - TypeBuilder tb = mob.DefineType("MyType", TypeAttributes.Public | TypeAttributes.Class); - MethodBuilder mb = tb.DefineMethod("SumMethod", MethodAttributes.Public | MethodAttributes.Static, - typeof(int), new Type[] {typeof(int), typeof(int)}); - ILGenerator il = mb.GetILGenerator(); - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Add); - il.Emit(OpCodes.Ret); - - Type type = tb.CreateType(); - - MethodInfo method = type.GetMethod("SumMethod"); - Console.WriteLine(method.Invoke(null, new object[] { 5, 10 })); -} -``` - -## Persisted dynamic assemblies in .NET - -In .NET, the type, which derives from , lets you save dynamic assemblies. For more information, see the usage scenarios and examples at [PersistedAssemblyBuilder](system-reflection-emit-persistedassemblybuilder.md). - -## Persisted dynamic assemblies in .NET Framework - -In .NET Framework, dynamic assemblies and modules can be saved to files. To support this feature, the enumeration declares two additional fields: and . - -The dynamic modules in the persistable dynamic assembly are saved when the dynamic assembly is saved using the method. To generate an executable, the method must be called to identify the method that is the entry point to the assembly. Assemblies are saved as DLLs by default, unless the method requests the generation of a console application or a Windows-based application. - -The following example demonstrates how to create, save, and run an assembly using .NET Framework. - -```csharp -public void CreateRunAndSaveAssembly(string assemblyPath) -{ - AssemblyBuilder ab = Thread.GetDomain().DefineDynamicAssembly(new AssemblyName("MyAssembly"), AssemblyBuilderAccess.RunAndSave); - ModuleBuilder mob = ab.DefineDynamicModule("MyAssembly.dll"); - TypeBuilder tb = mob.DefineType("MyType", TypeAttributes.Public | TypeAttributes.Class); - MethodBuilder meb = tb.DefineMethod("SumMethod", MethodAttributes.Public | MethodAttributes.Static, - typeof(int), new Type[] {typeof(int), typeof(int)}); - ILGenerator il = meb.GetILGenerator(); - il.Emit(OpCodes.Ldarg_0); - il.Emit(OpCodes.Ldarg_1); - il.Emit(OpCodes.Add); - il.Emit(OpCodes.Ret); - - Type type = tb.CreateType(); - - MethodInfo method = type.GetMethod("SumMethod"); - Console.WriteLine(method.Invoke(null, new object[] { 5, 10 })); - ab.Save("MyAssembly.dll"); -} -``` - -Some methods on the base class, such as `GetModules` and `GetLoadedModules`, won't work correctly when called from objects. You can load the defined dynamic assembly and call the methods on the loaded assembly. For example, to ensure that resource modules are included in the returned module list, call `GetModules` on the loaded object. If a dynamic assembly contains more than one dynamic module, the assembly's manifest file name should match the module's name that's specified as the first argument to the method. - -The signing of a dynamic assembly using is not effective until the assembly is saved to disk. So, strong names will not work with transient dynamic assemblies. - -Dynamic assemblies can reference types defined in another assembly. A transient dynamic assembly can safely reference types defined in another transient dynamic assembly, a persistable dynamic assembly, or a static assembly. However, the common language runtime does not allow a persistable dynamic module to reference a type defined in a transient dynamic module. This is because when the persisted dynamic module is loaded after being saved to disk, the runtime cannot resolve the references to types defined in the transient dynamic module. - -### Restrictions on emitting to remote application domains - -Some scenarios require a dynamic assembly to be created and executed in a remote application domain. Reflection emit does not allow a dynamic assembly to be emitted directly to a remote application domain. The solution is to emit the dynamic assembly in the current application domain, save the emitted dynamic assembly to disk, and then load the dynamic assembly into the remote application domain. The remoting and application domains are supported only in .NET Framework. diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicilinfo.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicilinfo.md deleted file mode 100644 index 60069de84f817..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicilinfo.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicILInfo class -description: Learn about the System.Reflection.Emit.DynamicILInfo class. -ms.date: 02/12/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Emit.DynamicILInfo class - -[!INCLUDE [context](includes/context.md)] - -Use the class to write your own MSIL generators instead of using . - -To create instances of other types, call methods, access fields, or reference types, the MSIL you generate must include tokens for those entities. The class provides several overloads of the method, which return tokens valid in the scope of the current . For example, if you need to call an overload of the method, you can obtain a for that overload and pass it to the method to obtain a token to embed in your MSIL. - -Once you have created arrays for your local variable signature, exceptions, and code body, you can use the , , and methods to insert them into the associated with your object. - -Generating your own metadata and MSIL requires familiarity with the Common Language Infrastructure (CLI) documentation, especially "Partition II: Metadata Definition and Semantics" and "Partition III: CIL Instruction Set". For more information, see [ECMA 335 Common Language Infrastructure (CLI)](https://www.ecma-international.org/publications-and-standards/standards/ecma-335/). - -> [!NOTE] -> Don't use to generate code that creates a delegate to another dynamic method by calling the delegate constructor directly. Instead, use the method to create the delegate. A delegate that is created with the delegate constructor doesn't have a reference to the target dynamic method. The dynamic method might be reclaimed by garbage collection while the delegate is still in use. diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md deleted file mode 100644 index 7895e6c9d2f74..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-createdelegate.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.CreateDelegate methods -description: Learn about the System.Reflection.Emit.DynamicMethod.CreateDelegate methods. -ms.date: 02/10/2026 -ai-usage: ai-assisted -dev_langs: - - CSharp - - VB ---- -# System.Reflection.Emit.DynamicMethod.CreateDelegate methods - -[!INCLUDE [context](includes/context.md)] - -## - -Calling the method or the method completes the dynamic method. Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown. - -To create a method body for a dynamic method when you have your own MSIL generator, call the method to obtain a object. If you don't have your own MSIL generator, call the method to obtain an object that can be used to generate the method body. - -### Examples - -The following code example creates a dynamic method that takes two parameters. The example emits a simple function body that prints the first parameter to the console, and the example uses the second parameter as the return value of the method. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the method. - -:::code language="csharp" source="./snippets/System.Reflection.Emit/DynamicMethod/.ctor/csharp/source1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Reflection.Emit/DynamicMethod/.ctor/vb/source1.vb" id="Snippet1"::: - -## - -This method overload creates a delegate bound to a particular object. Such a delegate is said to be closed over its first argument. Although the method is static, it acts as if it were an instance method; the instance is `target`. - -This method overload requires `target` to be of the same type as the first parameter of the dynamic method, or to be assignable to that type (for example, a derived class). The signature of `delegateType` has all the parameters of the dynamic method except the first. For example, if the dynamic method has the parameters , , and , then `delegateType` has the parameters and ; `target` is of type . - -Calling the method or the method completes the dynamic method. Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown. - -To create a method body for a dynamic method when you have your own MSIL generator, call the method to obtain a object. If you don't have your own MSIL generator, call the method to obtain an object that can be used to generate the method body. - -### Examples - -The following code example creates a delegate that binds a to an instance of a type, so that the method acts on the same instance each time it's invoked. - -The code example defines a class named `Example` with a private field, a class named `DerivedFromExample` that derives from the first class, a delegate type named `UseLikeStatic` that returns and has parameters of type `Example` and , and a delegate type named `UseLikeInstance` that returns and has one parameter of type . - -The example code then creates a that changes the private field of an instance of `Example` and returns the previous value. - -> [!NOTE] -> In general, changing the internal fields of classes isn't good object-oriented coding practice. - -The example code creates an instance of `Example` and then creates two delegates. The first is of type `UseLikeStatic`, which has the same parameters as the dynamic method. The second is of type `UseLikeInstance`, which lacks the first parameter (of type `Example`). This delegate is created using the method overload; the second parameter of that method overload is an instance of `Example`, in this case the instance just created, which is bound to the newly created delegate. Whenever that delegate is invoked, the dynamic method acts on the bound instance of `Example`. - -> [!NOTE] -> This is an example of the relaxed rules for delegate binding introduced in .NET Framework 2.0, along with new overloads of the method. For more information, see the class. - -The `UseLikeStatic` delegate is invoked, passing in the instance of `Example` that's bound to the `UseLikeInstance` delegate. Then the `UseLikeInstance` delegate is invoked, so that both delegates act on the same instance of `Example`. The changes in the values of the internal field are displayed after each call. Finally, a `UseLikeInstance` delegate is bound to an instance of `DerivedFromExample`, and the delegate calls are repeated. - -:::code language="csharp" source="./snippets/System.Reflection.Emit/DynamicMethod/.ctor/csharp/source.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Reflection.Emit/DynamicMethod/.ctor/vb/source.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md deleted file mode 100644 index 6678f3c2156de..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-ctor.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod constructors -description: Learn about the System.Reflection.Emit.DynamicMethod constructors. -ms.date: 02/10/2026 -ai-usage: ai-assisted -dev_langs: - - CSharp - - VB ---- -# System.Reflection.Emit.DynamicMethod constructors - -[!INCLUDE [context](includes/context.md)] - -## constructor - -The dynamic method that is created by this constructor is associated with an anonymous assembly instead of an existing type or module. The anonymous assembly exists only to provide a sandbox environment for dynamic methods, that is, to isolate them from other code. This environment makes it safe for the dynamic method to be emitted and executed by partially trusted code. - -Anonymously hosted dynamic methods don't have automatic access to any types or members that are `private`, `protected`, or `internal` (`Friend` in Visual Basic). This is different from dynamic methods that are associated with an existing type or module, which have access to hidden members in their associated scope. - -Specify `true` for `restrictedSkipVisibility` if your dynamic method has to access types or members that are `private`, `protected`, or `internal`. This gives the dynamic method restricted access to these members. That is, the members can be accessed only if the following conditions are met: - -- The target members belong to an assembly that has a level of trust equal to or lower than the call stack that emits the dynamic method. - -- The call stack that emits the dynamic method is granted with the flag. This is always true when the code is executed with full trust. For partially trusted code, it's true only if the host explicitly grants the permission. - - > [!IMPORTANT] - > If the permission hasn't been granted, a security exception is thrown when is called or when the dynamic method is invoked, not when this constructor is called. No special permissions are required to emit the dynamic method. - -For example, a dynamic method that's created with `restrictedSkipVisibility` set to `true` can access a private member of any assembly on the call stack if the call stack has been granted restricted member access. If the dynamic method is created with partially trusted code on the call stack, it can't access a private member of a type in a .NET Framework assembly, because such assemblies are fully trusted. - -If `restrictedSkipVisibility` is `false`, JIT visibility checks are enforced. The code in the dynamic method has access to public methods of public classes, and exceptions are thrown if it tries to access types or members that are `private`, `protected`, or `internal`. - -When an anonymously hosted dynamic method is constructed, the call stack of the emitting assembly is included. When the method is invoked, the permissions of the emitting call stack are used instead of the permissions of the actual caller. Thus, the dynamic method can't execute at a higher level of privilege than that of the assembly that emitted it, even if it's passed to and executed by an assembly that has a higher trust level. - -This constructor specifies the method attributes and , and the calling convention . - -> [!NOTE] -> This constructor was introduced in .NET Framework 3.5 or later. - -## constructor - -This constructor specifies method attributes and , calling convention , and doesn't skip just-in-time (JIT) visibility checks. - -The dynamic method created with this constructor has access to public and `internal` (`Friend` in Visual Basic) members of all the types contained in module `m`. - -> [!NOTE] -> For backward compatibility, this constructor demands with the flag if the following conditions are both true: `m` is a module other than the calling module, and the demand for with the flag has failed. If the demand for succeeds, the operation is allowed. - -### Examples - -The following code example creates a dynamic method that takes two parameters. The example emits a simple function body that prints the first parameter to the console, and the example uses the second parameter as the return value of the method. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the method. - -:::code language="csharp" source="./snippets/System.Reflection.Emit/DynamicMethod/.ctor/csharp/source1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Reflection.Emit/DynamicMethod/.ctor/vb/source1.vb" id="Snippet1"::: - -## constructor - -The dynamic method created with this constructor has access to all members of the type `owner`, and to public and `internal` (`Friend` in Visual Basic) members of all the other types in the module that contains `owner`. - -This constructor specifies method attributes and , calling convention , and doesn't skip just-in-time (JIT) visibility checks. - -> [!NOTE] -> For backward compatibility, this constructor demands with the flag if the following conditions are both true: `owner` is in a module other than the calling module, and the demand for with the flag has failed. If the demand for succeeds, the operation is allowed. - -### Examples - -The following code example creates a that's logically associated with a type. This association gives it access to the private members of that type. - -The code example defines a class named `Example` with a private field, a class named `DerivedFromExample` that derives from the first class, a delegate type named `UseLikeStatic` that returns and has parameters of type `Example` and , and a delegate type named `UseLikeInstance` that returns and has one parameter of type . - -The example code then creates a that changes the private field of an instance of `Example` and returns the previous value. - -> [!NOTE] -> In general, changing the internal fields of classes isn't good object-oriented coding practice. - -The example code creates an instance of `Example` and then creates two delegates. The first is of type `UseLikeStatic`, which has the same parameters as the dynamic method. The second is of type `UseLikeInstance`, which lacks the first parameter (of type `Example`). This delegate is created using the method overload; the second parameter of that method overload is an instance of `Example`, in this case the instance just created, which is bound to the newly created delegate. Whenever that delegate is invoked, the dynamic method acts on the bound instance of `Example`. - -> [!NOTE] -> This is an example of the relaxed rules for delegate binding introduced in .NET Framework 2.0, along with new overloads of the method. For more information, see the class. - -The `UseLikeStatic` delegate is invoked, passing in the instance of `Example` that's bound to the `UseLikeInstance` delegate. Then the `UseLikeInstance` delegate is invoked, so that both delegates act on the same instance of `Example`. The changes in the values of the internal field are displayed after each call. Finally, a `UseLikeInstance` delegate is bound to an instance of `DerivedFromExample`, and the delegate calls are repeated. - -:::code language="csharp" source="./snippets/System.Reflection.Emit/DynamicMethod/.ctor/csharp/source.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Reflection.Emit/DynamicMethod/.ctor/vb/source.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md deleted file mode 100644 index ab80ac9aaec08..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-getilgenerator.md +++ /dev/null @@ -1,40 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.GetILGenerator methods -description: Learn about the System.Reflection.Emit.DynamicMethod.GetILGenerator methods. -ms.date: 02/10/2026 -ai-usage: ai-assisted -dev_langs: - - CSharp - - VB ---- -# System.Reflection.Emit.DynamicMethod.GetILGenerator methods - -[!INCLUDE [context](includes/context.md)] - -## - -After a dynamic method has been completed, by calling the or method, any further attempt to add MSIL is ignored. No exception is thrown. - -> [!NOTE] -> There are restrictions on unverifiable code in dynamic methods, even in some full-trust scenarios. See the "Verification" section in Remarks for . - -### Examples - -The following code example creates a dynamic method that takes two parameters. The example emits a simple function body that prints the first parameter to the console, and the example uses the second parameter as the return value of the method. The example completes the method by creating a delegate, invokes the delegate with different parameters, and finally invokes the dynamic method using the method. - -:::code language="csharp" source="./snippets/System.Reflection.Emit/DynamicMethod/.ctor/csharp/source1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Reflection.Emit/DynamicMethod/.ctor/vb/source1.vb" id="Snippet1"::: - -## - -After a dynamic method has been completed, by calling the or method, any further attempt to add MSIL is ignored. No exception is thrown. - -> [!NOTE] -> There are restrictions on unverifiable code in dynamic methods, even in some full-trust scenarios. See the "Verification" section in Remarks for . - -### Examples - -The following code example demonstrates this method overload. This code example is part of a larger example provided for the class. - -:::code language="csharp" source="./snippets/System.Reflection.Emit/DynamicMethod/Overview/csharp/source.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Reflection.Emit/DynamicMethod/Overview/vb/source.vb" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md deleted file mode 100644 index 799c9a113072b..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-invoke.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.Invoke method -description: Learn about the System.Reflection.Emit.DynamicMethod.Invoke method. -ms.date: 02/10/2026 -ai-usage: ai-assisted -dev_langs: - - CSharp - - VB ---- -# System.Reflection.Emit.DynamicMethod.Invoke method - -[!INCLUDE [context](includes/context.md)] - -In addition to the listed exceptions, the calling code should be prepared to catch any exceptions thrown by the dynamic method. - -Executing a dynamic method with a delegate created by the method is more efficient than executing it with the method. - -Calling the method or the method completes the dynamic method. Any further attempt to alter the dynamic method, such as modifying parameter definitions or emitting more Microsoft intermediate language (MSIL), is ignored; no exception is thrown. - -All dynamic methods are static, so the `obj` parameter is always ignored. To treat a dynamic method as if it were an instance method, use the overload that takes an object instance. - -If the dynamic method has no parameters, the value of `parameters` should be `null`. Otherwise the number, type, and order of elements in the parameters array should be identical to the number, type, and order of parameters of the dynamic method. - -> [!NOTE] -> This method overload is called by the method overload inherited from the class, so the preceding remarks apply to both overloads. - -This method doesn't demand permissions directly, but invoking the dynamic method can result in security demands, depending on the method. For example, no demands are made for anonymously hosted dynamic methods that are created with the `restrictedSkipVisibility` parameter set to `false`. On the other hand, if you create a method with `restrictedSkipVisibility` set to `true` so it can access a hidden member of a target assembly, the method causes a demand for the permissions of the target assembly plus with the flag. - -## Examples - -The following code example invokes a dynamic method with exact binding, using the US-English culture. This code example is part of a larger example provided for the class. - -:::code language="csharp" source="./snippets/System.Reflection.Emit/DynamicMethod/Overview/csharp/source.cs" id="Snippet4"::: -:::code language="vb" source="./snippets/System.Reflection.Emit/DynamicMethod/Overview/vb/source.vb" id="Snippet4"::: diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md deleted file mode 100644 index b144c4a689389..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod-issecuritycritical.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod.IsSecurity* properties -description: Learn about the System.Reflection.Emit.DynamicMethod.IsSecurity* properties. -ms.date: 02/10/2026 -ai-usage: ai-assisted ---- -# System.Reflection.Emit.DynamicMethod.IsSecurity\* properties - -[!INCLUDE [context](includes/context.md)] - -> [!NOTE] -> The remarks in this article apply only to .NET Framework and not to modern .NET. - -The , , and properties report the transparency level of the dynamic method as determined by the common language runtime (CLR). The combinations of these properties are shown in the following table: - -| Security level | IsSecurityCritical | IsSecuritySafeCritical | IsSecurityTransparent | -|----------------|--------------------|-----------------------|-----------------------| -| Critical | `true` | `false` | `false` | -| Safe critical | `true` | `true` | `false` | -| Transparent | `false` | `false` | `true` | - -Using these properties is much simpler than examining the security annotations of an assembly and its types, checking the current trust level, and attempting to duplicate the runtime's rules. - -The transparency of a dynamic method depends on the module it's associated with. If the dynamic method is associated with a type rather than a module, its transparency depends on the module that contains the type. Dynamic methods don't have security annotations, so they're assigned the default transparency for the associated module. - -- Anonymously hosted dynamic methods are always transparent, because the system-provided module that contains them is transparent. - -- The transparency of a dynamic method that's associated with a trusted assembly (that is, a strong-named assembly that's installed in the global assembly cache) is described in the following table. - - | Assembly annotation | Level 1 transparency | Level 2 transparency | - |---------------------|----------------------|----------------------| - | Fully transparent | Transparent | Transparent | - | Fully critical | Critical | Critical | - | Mixed transparency | Transparent | Transparent | - | Security-agnostic | Safe-critical | Critical | - - For example, if you associate a dynamic method with a type that's in mscorlib.dll, which has level 2 mixed transparency, the dynamic method is transparent and can't execute critical code. For information about transparency levels, see [Security-Transparent Code, Level 1](/dotnet/framework/misc/security-transparent-code-level-1) and [Security-Transparent Code, Level 2](/dotnet/framework/misc/security-transparent-code-level-2). - - > [!NOTE] - > Associating a dynamic method with a module in a trusted level 1 assembly that's security-agnostic, such as System.dll, doesn't permit elevation of trust. If the grant set of the code that calls the dynamic method doesn't include the grant set of System.dll (that is, full trust), is thrown when the dynamic method is called. - -- The transparency of a dynamic method that's associated with a partially trusted assembly depends on how the assembly is loaded. If the assembly is loaded with partial trust (for example, into a sandboxed application domain), the runtime ignores the security annotations of the assembly. The assembly and all its types and members, including dynamic methods, are treated as transparent. The runtime pays attention to security annotations only if the partial-trust assembly is loaded with full trust (for example, into the default application domain of a desktop application). In that case, the runtime assigns the dynamic method the default transparency for methods according to the assembly's annotations. - -For more information about reflection emit and transparency, see [Security Issues in Reflection Emit](../../framework/reflection-and-codedom/security-issues-in-reflection-emit.md). For information about transparency, see [Security Changes](/dotnet/framework/security/security-changes). diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod.md deleted file mode 100644 index c0e468fb99988..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-dynamicmethod.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: System.Reflection.Emit.DynamicMethod class -description: Learn about the System.Reflection.Emit.DynamicMethod class. -ms.date: 12/31/2023 ---- -# System.Reflection.Emit.DynamicMethod class - -[!INCLUDE [context](includes/context.md)] - -You can use the class to generate and execute a method at runtime, without having to generate a dynamic assembly and a dynamic type to contain the method. The executable code created by the just-in-time (JIT) compiler is reclaimed when the object is reclaimed. Dynamic methods are the most efficient way to generate and execute small amounts of code. - -A dynamic method can be anonymously hosted, or it can be logically associated with a module or with a type. - -- If the dynamic method is anonymously hosted, it is located in a system-provided assembly, and therefore is isolated from other code. By default, it does not have access to any non-public data. An anonymously hosted dynamic method can have restricted ability to skip the JIT compiler's visibility checks, if it has been granted with the flag. The trust level of the assembly whose non-public members are accessed by the dynamic method must be equal to, or a subset of, the trust level of the call stack that emitted the dynamic method. For more information about anonymously hosted dynamic methods, see [Walkthrough: Emitting Code in Partial Trust Scenarios](../../framework/reflection-and-codedom/walkthrough-emitting-code-in-partial-trust-scenarios.md). - -- If the dynamic method is associated with a module that you specify, the dynamic method is effectively global to that module. It can access all types in the module and all `internal` (`Friend` in Visual Basic) members of the types. You can associate a dynamic method with any module, regardless of whether you created the module, provided that a demand for with the flag can be satisfied by the call stack that includes your code. If the flag is included in the grant, the dynamic method can skip the JIT compiler's visibility checks and access the private data of all types declared in the module or in any other module in any assembly. - - > [!NOTE] - > When you specify the module with which a dynamic method is associated, that module must not be in the system-provided assembly that is used for anonymous hosting. - -- If the dynamic method is associated with a type that you specify, it has access to all members of the type, regardless of access level. In addition, JIT visibility checks can be skipped. This gives the dynamic method access to the private data of other types declared in the same module or in any other module in any assembly. You can associate a dynamic method with any type, but your code must be granted with both the and flags. - -The following table shows which types and members are accessible to an anonymously hosted dynamic method, with and without JIT visibility checks, depending on whether with the flag is granted. - -| Visibility checks | Without `RestrictedMemberAccess` | With `RestrictedMemberAccess` | -|-------------------|----------------------------------|-------------------------------| -|Without skipping JIT visibility checks|Public members of public types in any assembly.|Public members of public types in any assembly.| -|Skipping JIT visibility checks, with restrictions|Public members of public types in any assembly.|All members of all types, only in assemblies whose trust levels are equal to or less than the trust level of the assembly that emitted the dynamic method.| - -The following table shows which types and members are accessible to a dynamic method that's associated with a module or with a type in a module. - -| Skip JIT visibility checks | Associated with module | Associated with type | -|----------------------------|------------------------|----------------------| -| No |Public and internal members of public, internal, and private types in the module.

Public members of public types in any assembly.|All members of the associated type. Public and internal members of all the other types in the module.

Public members of public types in any assembly.| -| Yes |All members of all types in any assembly.|All members of all types in any assembly.| - -A dynamic method that is associated with a module has the permissions of that module. A dynamic method that is associated with a type has the permissions of the module containing that type. - -Dynamic methods and their parameters do not have to be named, but you can specify names to assist in debugging. Custom attributes are not supported on dynamic methods or their parameters. - -Although dynamic methods are `static` methods (`Shared` methods in Visual Basic), the relaxed rules for delegate binding allow a dynamic method to be bound to an object, so that it acts like an instance method when called using that delegate instance. An example that demonstrates this is provided for the method overload. - -## Verification - -The following list summarizes the conditions under which dynamic methods can contain unverifiable code. (For example, a dynamic method is unverifiable if its property is set to `false`.) - -- A dynamic method that's associated with a security-critical assembly is also security-critical, and can skip verification. For example, an assembly without security attributes that is run as a desktop application is treated as security-critical by the runtime. If you associate a dynamic method with the assembly, the dynamic method can contain unverifiable code. -- If a dynamic method that contains unverifiable code is associated with an assembly that has level 1 transparency, the just-in-time (JIT) compiler injects a security demand. The demand succeeds only if the dynamic method is executed by fully trusted code. See [Security-Transparent Code, Level 1](/dotnet/framework/misc/security-transparent-code-level-1). -- If a dynamic method that contains unverifiable code is associated with an assembly that has level 2 transparency (such as mscorlib.dll), it throws an exception (injected by the JIT compiler) instead of making a security demand. See [Security-Transparent Code, Level 2](/dotnet/framework/misc/security-transparent-code-level-2). -- An anonymously hosted dynamic method that contains unverifiable code always throws an exception. It can never skip verification, even if it is created and executed by fully trusted code. - -The exception that's thrown for unverifiable code varies depending on the way the dynamic method is invoked. If you invoke a dynamic method by using a delegate returned from the method, a is thrown. If you invoke the dynamic method by using the method, a is thrown with an inner . diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-methodbuilder.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-methodbuilder.md deleted file mode 100644 index 7fd1afe4b3f28..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-methodbuilder.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: System.Reflection.Emit.MethodBuilder class -description: Learn about the System.Reflection.Emit.MethodBuilder class. -ms.date: 12/31/2023 ---- -# System.Reflection.Emit.MethodBuilder class - -[!INCLUDE [context](includes/context.md)] - -The class is used to fully describe a method in common intermediate language (CIL), including the name, attributes, signature, and method body. It is used in conjunction with the class to create classes at runtime. - -You can use reflection emit to define global methods and to define methods as type members. The APIs that define methods return objects. - -## Global methods - -A global method is defined by using the method, which returns a `MethodBuilder` object. - -Global methods must be static. If a dynamic module contains global methods, the method must be called before persisting the dynamic module or the containing dynamic assembly because the common language runtime postpones fixing up the dynamic module until all global functions have been defined. - -A global native method is defined by using the method. Platform invoke (PInvoke) methods must not be declared abstract or virtual. The runtime sets the attribute for a platform invoke method. - -## Methods as members of types - -A method is defined as a type member by using the method, which returns a object. - -The method is used to set the name and parameter attributes of a parameter, or of the return value. The object returned by this method represents a parameter or the return value. The object can be used to set the marshaling, to set the constant value, and to apply custom attributes. - -## Attributes - -Members of the enumeration define the precise character of a dynamic method: - -- Static methods are specified using the attribute. -- Final methods (methods that cannot be overridden) are specified using the attribute. -- Virtual methods are specified using the attribute. -- Abstract methods are specified using the attribute. -- Several attributes determine method visibility. See the description of the enumeration. -- Methods that implement overloaded operators must set the attribute. -- Finalizers must set the attribute. - -## Known issues - -- Although is derived from , some of the abstract methods defined in the class are not fully implemented in . These methods throw the . For example the method is not fully implemented. You can reflect on these methods by retrieving the enclosing type using the or methods. -- Custom modifiers are supported. diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-persistedassemblybuilder.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-persistedassemblybuilder.md deleted file mode 100644 index f9758897ffddd..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-persistedassemblybuilder.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: System.Reflection.Emit.PersistedAssemblyBuilder class -description: Learn about the System.Reflection.Emit.PersistedAssemblyBuilder class. -ms.date: 05/10/2024 ---- -# Persisted dynamic assemblies in .NET - -[!INCLUDE [context](includes/context.md)] - -The API wasn't originally ported to .NET (Core) because the implementation depended heavily on Windows-specific native code that also wasn't ported. .NET 9 added the class, which provides a fully managed `Reflection.Emit` implementation that supports saving. This implementation has no dependency on the pre-existing, runtime-specific `Reflection.Emit` implementation. That is, now there are two different implementations in .NET: *runnable* and *persisted*. To run the persisted assembly, first save it into a memory stream or a file, then load it back. - -Before `PersistedAssemblyBuilder`, you could only run a generated assembly and not save it. Since the assembly was in-memory only, it was difficult to debug. Advantages of saving a dynamic assembly to a file are: - -- You can verify the generated assembly with tools such as ILVerify, or decompile and manually examine it with tools such as ILSpy. -- The saved assembly can be loaded directly, without needing to compile again, which can decrease application startup time. - -To create a `PersistedAssemblyBuilder` instance, use the constructor. The `coreAssembly` parameter is used to resolve base runtime types and can be used for resolving reference assembly versioning: - -- If `Reflection.Emit` is used to generate an assembly that will only be executed on the same runtime version as the runtime version that the compiler is running on (typically in-proc), the core assembly can be simply `typeof(object).Assembly`. The following example demonstrates how to create and save an assembly to a stream and run it with the current runtime assembly: - - :::code language="csharp" source="./snippets/System.Reflection.Emit/PersistedAssemblyBuilder/Overview/csharp/CreateAndRunAssembly.cs" id="Snippet1"::: - -- If `Reflection.Emit` is used to generate an assembly that targets a specific TFM, open the reference assemblies for the given TFM using `MetadataLoadContext` and use the value of the [MetadataLoadContext.CoreAssembly](xref:System.Reflection.MetadataLoadContext.CoreAssembly) property for `coreAssembly`. This value allows the generator to run on one .NET runtime version and target a different .NET runtime version. You should use types returned by the `MetadataLoadContext` instance when referencing core types. For example, instead of `typeof(int)`, find the `System.Int32` type in `MetadataLoadContext.CoreAssembly` by name: - - :::code language="csharp" source="./snippets/System.Reflection.Emit/PersistedAssemblyBuilder/Overview/csharp/CreateAndRunAssembly.cs" id="Snippet2"::: - -## Set entry point for an executable - -To set the entry point for an executable or to set other options for the assembly file, you can call the `public MetadataBuilder GenerateMetadata(out BlobBuilder ilStream, out BlobBuilder mappedFieldData)` method and use the populated metadata to generate the assembly with desired options, for example: - -:::code language="csharp" source="./snippets/System.Reflection.Emit/PersistedAssemblyBuilder/Overview/csharp/GenerateMetadataSnippets.cs" id="Snippet1"::: - -## Emit symbols and generate PDB - -The symbols metadata is populated into the `pdbBuilder` out parameter when you call the method on a `PersistedAssemblyBuilder` instance. To create an assembly with a portable PDB: - -1. Create instances with the method. While emitting the method's IL, also emit the corresponding symbol info. -2. Create a instance using the `pdbBuilder` instance produced by the method. -3. Serialize the `PortablePdbBuilder` into a , and write the `Blob` into a PDB file stream (only if you're generating a standalone PDB). -4. Create a instance and add a (standalone PDB) or . -5. Set the optional `debugDirectoryBuilder` argument when creating the instance. - -The following example shows how to emit symbol info and generate a PDB file. - -```csharp -static void GenerateAssemblyWithPdb() -{ - PersistedAssemblyBuilder ab = new PersistedAssemblyBuilder(new AssemblyName("MyAssembly"), typeof(object).Assembly); - ModuleBuilder mb = ab.DefineDynamicModule("MyModule"); - TypeBuilder tb = mb.DefineType("MyType", TypeAttributes.Public | TypeAttributes.Class); - MethodBuilder mb1 = tb.DefineMethod("SumMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(int), [typeof(int), typeof(int)]); - ISymbolDocumentWriter srcDoc = mb.DefineDocument("MySourceFile.cs", SymLanguageType.CSharp); - ILGenerator il = mb1.GetILGenerator(); - LocalBuilder local = il.DeclareLocal(typeof(int)); - local.SetLocalSymInfo("myLocal"); - il.MarkSequencePoint(srcDoc, 7, 0, 7, 11); - ... - il.Emit(OpCodes.Ret); - - MethodBuilder entryPoint = tb.DefineMethod("Main", MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Static); - ILGenerator il2 = entryPoint.GetILGenerator(); - il2.BeginScope(); - ... - il2.EndScope(); - ... - tb.CreateType(); - - MetadataBuilder metadataBuilder = ab.GenerateMetadata(out BlobBuilder ilStream, out _, out MetadataBuilder pdbBuilder); - MethodDefinitionHandle entryPointHandle = MetadataTokens.MethodDefinitionHandle(entryPoint.MetadataToken); - DebugDirectoryBuilder debugDirectoryBuilder = GeneratePdb(pdbBuilder, metadataBuilder.GetRowCounts(), entryPointHandle); - - ManagedPEBuilder peBuilder = new ManagedPEBuilder( - header: new PEHeaderBuilder(imageCharacteristics: Characteristics.ExecutableImage, subsystem: Subsystem.WindowsCui), - metadataRootBuilder: new MetadataRootBuilder(metadataBuilder), - ilStream: ilStream, - debugDirectoryBuilder: debugDirectoryBuilder, - entryPoint: entryPointHandle); - - BlobBuilder peBlob = new BlobBuilder(); - peBuilder.Serialize(peBlob); - - using var fileStream = new FileStream("MyAssembly.exe", FileMode.Create, FileAccess.Write); - peBlob.WriteContentTo(fileStream); -} - -static DebugDirectoryBuilder GeneratePdb(MetadataBuilder pdbBuilder, ImmutableArray rowCounts, MethodDefinitionHandle entryPointHandle) -{ - BlobBuilder portablePdbBlob = new BlobBuilder(); - PortablePdbBuilder portablePdbBuilder = new PortablePdbBuilder(pdbBuilder, rowCounts, entryPointHandle); - BlobContentId pdbContentId = portablePdbBuilder.Serialize(portablePdbBlob); - // In case saving PDB to a file - using FileStream fileStream = new FileStream("MyAssemblyEmbeddedSource.pdb", FileMode.Create, FileAccess.Write); - portablePdbBlob.WriteContentTo(fileStream); - - DebugDirectoryBuilder debugDirectoryBuilder = new DebugDirectoryBuilder(); - debugDirectoryBuilder.AddCodeViewEntry("MyAssemblyEmbeddedSource.pdb", pdbContentId, portablePdbBuilder.FormatVersion); - // In case embedded in PE: - // debugDirectoryBuilder.AddEmbeddedPortablePdbEntry(portablePdbBlob, portablePdbBuilder.FormatVersion); - return debugDirectoryBuilder; -} -``` - -Further, you can add by calling the method from the `pdbBuilder` instance to add source embedding and source indexing advanced PDB information. - -```csharp -private static void EmbedSource(MetadataBuilder pdbBuilder) -{ - byte[] sourceBytes = File.ReadAllBytes("MySourceFile2.cs"); - BlobBuilder sourceBlob = new BlobBuilder(); - sourceBlob.WriteBytes(sourceBytes); - pdbBuilder.AddCustomDebugInformation(MetadataTokens.DocumentHandle(1), - pdbBuilder.GetOrAddGuid(new Guid("0E8A571B-6926-466E-B4AD-8AB04611F5FE")), pdbBuilder.GetOrAddBlob(sourceBlob)); -} -``` - -## Add resources with PersistedAssemblyBuilder - -You can call to add as many resources as needed. Streams must be concatenated into one that you pass into the argument. -The following example shows how to create resources and attach it to the assembly that's created. - -:::code language="csharp" source="./snippets/System.Reflection.Emit/PersistedAssemblyBuilder/Overview/csharp/GenerateMetadataSnippets.cs" id="Snippet2"::: - -The following example shows how to read resources from the created assembly. - -:::code language="csharp" source="./snippets/System.Reflection.Emit/PersistedAssemblyBuilder/Overview/csharp/GenerateMetadataSnippets.cs" id="Snippet3"::: - -> [!NOTE] -> The metadata tokens for all members are populated on the operation. Don't use the tokens of a generated type and its members before saving, as they'll have default values or throw exceptions. It's safe to use tokens for types that are referenced, not generated. -> -> Some APIs that aren't important for emitting an assembly aren't implemented; for example, `GetCustomAttributes()` is not implemented. With the runtime implementation, you were able to use those APIs after creating the type. For the persisted `AssemblyBuilder`, they throw `NotSupportedException` or `NotImplementedException`. If you have a scenario that requires those APIs, file an issue in the [dotnet/runtime repo](https://github.com/dotnet/runtime). - -For an alternative way to generate assembly files, see . diff --git a/docs/fundamentals/runtime-libraries/system-reflection-emit-typebuilder.md b/docs/fundamentals/runtime-libraries/system-reflection-emit-typebuilder.md deleted file mode 100644 index df14a8f98480d..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-emit-typebuilder.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: System.Reflection.Emit.TypeBuilder class -description: Learn about the System.Reflection.Emit.TypeBuilder class. -ms.date: 12/31/2023 ---- -# System.Reflection.Emit.TypeBuilder class - -[!INCLUDE [context](includes/context.md)] - - is the root class used to control the creation of dynamic classes in the runtime. It provides a set of routines that are used to define classes, add methods and fields, and create the class inside a module. A new can be created from a dynamic module by calling the method, which returns a object. - -Reflection emit provides the following options for defining types: - -- Define a class or interface with the given name. -- Define a class or interface with the given name and attributes. -- Define a class with the given name, attributes, and base class. -- Define a class with the given name, attributes, base class, and the set of interfaces that the class implements. -- Define a class with the given name, attributes, base class, and packing size. -- Define a class with the given name, attributes, base class, and the class size as a whole. -- Define a class with the given name, attributes, base class, packing size, and the class size as a whole. - -To create an array type, pointer type, or byref type for an incomplete type that is represented by a object, use the method, method, or method, respectively. - -Before a type is used, the method must be called. **CreateType** completes the creation of the type. Following the call to **CreateType**, the caller can instantiate the type by using the method, and invoke members of the type by using the method. It is an error to invoke methods that change the implementation of a type after **CreateType** has been called. For example, the common language runtime throws an exception if the caller tries to add new members to a type. - -A class initializer is created by using the method. **DefineTypeInitializer** returns a object. - -Nested types are defined by calling one of the methods. - -## Attributes - -The class uses the enumeration to further specify the characteristics of the type to be created: - -- Interfaces are specified using the and attributes. -- Concrete classes (classes that cannot be extended) are specified using the attribute. -- Several attributes determine type visibility. See the description of the enumeration. -- If is specified, the class loader lays out fields in the order they are read from metadata. The class loader considers the specified packing size but ignores any specified field offsets. The metadata preserves the order in which the field definitions are emitted. Even across a merge, the metadata will not reorder the field definitions. The loader will honor the specified field offsets only if is specified. - -## Known issues - -- Reflection emit does not verify whether a non-abstract class that implements an interface has implemented all the methods declared in the interface. However, if the class does not implement all the methods declared in an interface, the runtime does not load the class. -- Although is derived from , some of the abstract methods defined in the class are not fully implemented in the class. Calls to these methods throw a exception. The desired functionality can be obtained by retrieving the created type using the or and reflecting on the retrieved type. diff --git a/docs/fundamentals/runtime-libraries/system-reflection-portableexecutable-debugdirectoryentrytype.md b/docs/fundamentals/runtime-libraries/system-reflection-portableexecutable-debugdirectoryentrytype.md deleted file mode 100644 index 17fe074620f2b..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-reflection-portableexecutable-debugdirectoryentrytype.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: System.Reflection.PortableExecutable.DebugDirectoryEntryType enum -description: Learn about the System.Reflection.PortableExecutable.DebugDirectoryEntryType enum. -ms.date: 12/31/2023 ---- -# System.Reflection.PortableExecutable.DebugDirectoryEntryType enum - -[!INCLUDE [context](includes/context.md)] - -The enum describes the format of the debugging information of a . - -See the following for the specifications related to individual enumeration members: - -|Member|Specification| -|---|---| -|`CodeView`|[CodeView Debug Directory Entry (type 2)](https://github.com/dotnet/runtime/blob/main/docs/design/specs/PE-COFF.md#codeview-debug-directory-entry-type-2)| -|`EmbeddedPortablePdb`|[Embedded Portable PDB Debug Directory Entry (type 17)](https://github.com/dotnet/runtime/blob/main/docs/design/specs/PE-COFF.md#embedded-portable-pdb-debug-directory-entry-type-17)| -|`PdbChecksum`|[PDB Checksum Debug Directory Entry (type 19)](https://github.com/dotnet/runtime/blob/main/docs/design/specs/PE-COFF.md#pdb-checksum-debug-directory-entry-type-19)| -|`Reproducible`|See [Deterministic Debug Directory Entry (type 16)](https://github.com/dotnet/runtime/blob/main/docs/design/specs/PE-COFF.md#deterministic-debug-directory-entry-type-16)| - -## DebugDirectoryEntryType.Reproducible - -The tool that produced the deterministic PE/COFF file guarantees that the entire content of the file is based solely on documented inputs given to the tool (such as source files, resource files, compiler options, etc.) rather than ambient environment variables (such as the current time, the operating system, the bitness of the process running the tool, etc.). - -The value of the `TimeDateStamp` field in the COFF File Header of a deterministic PE/COFF file does not indicate the date and time when the file was produced and should not be interpreted that way. Instead, the value of the field is derived from a hash of the file content. The algorithm to calculate this value is an implementation detail of the tool that produced the file. - -The debug directory entry of type must have all fields except for zeroed. diff --git a/docs/fundamentals/runtime-libraries/system-resources-missingmanifestresourceexception.md b/docs/fundamentals/runtime-libraries/system-resources-missingmanifestresourceexception.md deleted file mode 100644 index 6f430394e8c92..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-resources-missingmanifestresourceexception.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: System.Resources.MissingManifestResourceException class -description: Learn about the System.Resources.MissingManifestResourceException class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Resources.MissingManifestResourceException class - -[!INCLUDE [context](includes/context.md)] - -A exception is thrown for different reasons in .NET versus UWP apps. - -## .NET apps - -In .NET apps, is thrown when the attempt to retrieve a resource fails because the resource set for the neutral culture could not be loaded from a particular assembly. Although the exception is thrown when you try to retrieve a particular resource, it is caused by the failure to load the resource set rather than the failure to find the resource. - -> [!NOTE] -> For additional information, see the "Handling a MissingManifestResourceException Exception" section in the class topic. - -The main causes of the exception include the following: - -- The resource set is not identified by its fully qualified name. For example, if the `baseName` parameter in the call to the method specifies the root name of the resource set without a namespace, but the resource set is assigned a namespace when it is stored in its assembly, the call to the method throws this exception. - - If you've embedded the .resources file that contains the default culture's resources in your executable and your app is throwing a , you can use a reflection tool such as the [IL Disassembler (Ildasm.exe)](../../framework/tools/ildasm-exe-il-disassembler.md) to determine the fully qualified name of the resource. In ILDasm, double click the executable's **MANIFEST** label to open the **MANIFEST** window. Resources appear as `.mresource` items and are listed after external assembly references and custom assembly-level attributes. You can also compile the following simple utility, which lists the fully qualified names of embedded resources in the assembly whose name is passed to it as a command-line parameter. - - :::code language="csharp" source="./snippets/System.Resources/MissingManifestResourceException/Overview/csharp/resourcenames.cs" id="Snippet4"::: - :::code language="vb" source="./snippets/System.Resources/ResourceManager/Overview/vb/resourcenames.vb" id="Snippet4"::: - -- You identify the resource set by its resource file name (along with its optional namespace) and its file extension rather than by its namespace and root file name alone. For example, this exception is thrown if the neutral culture's resource set is named `GlobalResources` and you supply a value of `GlobalResources.resources` (instead of `GlobalResources`) to the `baseName` parameter of the constructor. - -- The culture-specific resource set that is identified in a method call cannot be found, and the fallback resource set cannot be loaded. For example, if you create satellite assemblies for the English (United States) and Russia (Russian) cultures but you fail to provide a resource set for the neutral culture, this exception is thrown if your app's current culture is English (United Kingdom). - - uses the HRESULT `COR_E_MISSINGMANIFESTRESOURCE`, which has the value 0x80131532. - - uses the default implementation, which supports reference equality. - -For a list of initial property values for an instance of , see the constructors. - -> [!NOTE] -> We recommend that you include a neutral set of resources in your main assembly, so your app won't fail if a satellite assembly is unavailable. - -## Universal Windows Platform (UWP) apps - -UWP apps deploy resources for multiple cultures, including the neutral culture, in a single package resource index (.pri) file. As a result, in a UWP app, if resources for the preferred culture cannot be found, the is thrown under either of the following conditions: - -- The app does not include a .pri file, or the .pri file could not be opened. -- The app's .pri file does not contain a resource set for the given root name. diff --git a/docs/fundamentals/runtime-libraries/system-resources-neutralresourceslanguageattribute.md b/docs/fundamentals/runtime-libraries/system-resources-neutralresourceslanguageattribute.md deleted file mode 100644 index e8d78cd700c7e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-resources-neutralresourceslanguageattribute.md +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: System.Resources.NeutralResourcesLanguageAttribute class -description: Learn about the System.Resources.NeutralResourcesLanguageAttribute class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Resources.NeutralResourcesLanguageAttribute class - -[!INCLUDE [context](includes/context.md)] - -In desktop apps, the attribute informs the resource manager of an app's default culture and the location of its resources. By default, resources are embedded in the main app assembly, and you can use the attribute as follows. This statement specifies that the English (United States) is the app's default culture. - -```csharp -[assembly: NeutralResourcesLanguage("en-US")] -``` - -```vb - -``` - -You can also use the attribute to indicate where can find the resources of the default culture by providing an enumeration value in the attribute statement. This is most commonly done to indicate that the resources reside in a satellite assembly. For example, the following statement specifies that English (United States) is the app's default or neutral culture and that its resources reside in a satellite assembly. The object will look for them in a subdirectory named en-US. - -```csharp -[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] -``` - -```vb - -``` - -> [!TIP] -> We recommend that you always use the attribute to define the default culture of your app. - -The attribute performs two roles: - -- If the default culture's resources are embedded in the app's main assembly and has to retrieve resources that belong to the same culture as the default culture, the automatically uses the resources located in the main assembly instead of searching for a satellite assembly. This bypasses the usual assembly probe, improves lookup performance for the first resource you load, and can reduce your working set. See [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps) for the process uses to probe for resource files. - -- If the default culture's resources are located in a satellite assembly rather than in the main app assembly, the attribute specifies the culture and the directory from which the runtime can load the resources. - -## Windows 8.x Store apps - -In Windows 8.x Store apps whose resources are loaded and retrieved by using the class, the attribute defines the neutral culture whose resources are used in the event of a failed probe. It does not specify the location of the resources. By default, uses the app's package resource index (PRI) file to locate the resources of the default culture. The neutral culture that is defined by the attribute is added to the end of the UI language list to simulate this effect. - -If you load and retrieve resources by using the Windows Runtime[Windows.ApplicationModel.Resources.ResourceLoader](https://go.microsoft.com/fwlink/p/?LinkId=238182) class or the types in the [Windows.ApplicationModel.Resources.Core](https://go.microsoft.com/fwlink/p/?LinkId=238194) namespace, the attribute is ignored. - -## Examples - -The following example uses a simple "Hello World" app to illustrate the use of the attribute to define a default or fallback culture. It requires the creation of separate resource files for the English (en), English (United States) (en-US), and French (France) (fr-FR) cultures. The following shows the contents of a text file named ExampleResources.txt for the English culture. - -``` -# Resources for the default (en) culture. -Greeting=Hello -``` - -To use the resource file in an app, you must use the [Resource File Generator (Resgen.exe)](../../framework/tools/resgen-exe-resource-file-generator.md) to convert the file from its text (.txt) format to a binary (.resources) format as follows: - -``` -resgen ExampleResources.txt -``` - -When the app is compiled, the binary resource file will be embedded in the main app assembly. - -The following shows the contents of a text file named ExampleResources.en-US.txt that provides resources for the English (United States) culture. - -``` -# Resources for the en-US culture. -Greeting=Hi -``` - -The text file can be converted to a binary resources file by using the [Resource File Generator (ResGen.exe)](../../framework/tools/resgen-exe-resource-file-generator.md) at the command line as follows: - -``` -resgen ExampleResources.en-US.txt ExampleResources.en-US.resources -``` - -The binary resource file should then be compiled into an assembly by using [Assembly Linker (Al.exe)](../../framework/tools/al-exe-assembly-linker.md) and placed in the en-US subdirectory of the app directory by issuing the following command: - -``` -al /t:lib /embed:ExampleResources.en-US.resources /culture:en-US /out:en-us\Example.resources.dll -``` - -The following shows the contents of a text file named ExampleResources.fr-FR.txt that provides resources for the French (France) culture. - -``` -# Resources for the fr-FR culture. -Greeting=Bonjour -``` - -The text file can be converted to a binary resource file by using ResGen.exe at the command line as follows: - -``` -resgen ExampleResources.fr-FR.txt ExampleResources.fr-FR.resources -``` - -The binary resources file should then be compiled into an assembly by using Assembly Linker and placed in the fr-FR subdirectory of the app directory by issuing the following command: - -``` -al /t:lib /embed:ExampleResources.fr-FR.resources /culture:fr-FR /out:fr-FR\Example.resources.dll -``` - -The following example provides the executable code that sets the current culture, prompts for the user's name, and displays a localized string. - -:::code language="csharp" source="./snippets/System.Resources/NeutralResourcesLanguageAttribute/Overview/csharp/example.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Resources/NeutralResourcesLanguageAttribute/Overview/vb/example.vb" id="Snippet1"::: - -It can be compiled by using the following command in Visual Basic: - -``` -vbc Example.vb /resource:ExampleResources.resources -``` - -or by using the following command in C#: - -``` -csc Example.cs /resource:ExampleResources.resources -``` diff --git a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-ctor.md b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-ctor.md deleted file mode 100644 index 7b902488b1562..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-ctor.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: System.Resources.ResourceManager constructors -description: Learn about the System.Resources.ResourceManager constructors. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - VB ---- -# System.Resources.ResourceManager constructors - -[!INCLUDE [context](includes/context.md)] - -## constructor - -This section pertains to the constructor overload. - -### Desktop apps - -In desktop apps, the resource manager uses the `resourceSource` parameter to load a particular resource file as follows: - -- If the attribute is not used to indicate that the resources of the default culture reside in a satellite assembly, the resource manager assumes that the resource file for the default culture is found in the same assembly as the type specified by the `resourceSource` parameter. -- The resource manager assumes that the default resource file has the same base name as the type specified by the `resourceSource` parameter. -- The resource manager uses the default class to manipulate the resource file. - -For example, given a type named `MyCompany.MyProduct.MyType`, the resource manager looks for a *.resources* file named *MyCompany.MyProduct.MyType.resources* in the assembly that defines `MyType`. - -In Visual Studio, the Resource Designer automatically generates code that defines an `internal` (in C#) or `Friend` (in Visual Basic) class whose name is the same as the base name of the *.resources* file for the default culture. This makes it possible to instantiate a object and couple it with a particular set of resources by getting a type object whose name corresponds to the name of the resource, because as long as the class is visible to the compiler, the resources must be as well. For example, if a *.resources* file is named Resource1, the following statement instantiates a object to manage the *.resources* file named Resource1: - -:::code language="csharp" source="./snippets/System.Resources/ResourceManager/.ctor/csharp/ctor1.cs" id="Snippet2"::: - -If you're not using Visual Studio, you can create a class with no members whose namespace and name are the same as that of the default *.resources* file. The example provides an illustration. - -### Windows 8.x apps - -> [!IMPORTANT] -> Although the class is supported in Windows 8.x apps, we do not recommend its use. Use this class only when you develop Portable Class Library projects that can be used with Windows 8.x apps. To retrieve resources from Windows 8.x apps, use the [Windows.ApplicationModel.Resources.ResourceLoader](/uwp/api/windows.applicationmodel.resources.resourceloader) class instead. - -In Windows 8.x apps, uses the `resourceSource` parameter to infer the assembly, base name, and the namespace where the resource items can be located within the app's package resource index (PRI) file. For example, given a type named `MyCompany.MyProduct.MyType` that's defined in `MyAssembly`, the resource manager looks for a resource set identifier named `MyAssembly` and looks for a scope `MyCompany.MyProduct.MyType` within that resource set. The resource manager searches for resource items under the default context (current culture, current high contrast setting, and so on) within this scope. - -### Example - -The following example uses the constructor to instantiate a object. It consists of resources compiled from .txt files for the English (en), French (France) (fr-FR), and Russian (Russia) (ru-RU) cultures. The example changes the current culture and current UI culture to English (United States), French (France), Russian (Russia), and Swedish (Sweden). It then calls the method to retrieve the localized string, which displays a greeting that depends on the time of day. - -The example requires three text-based resource files, as listed in the following table. Each file includes string resources named `Morning`, `Afternoon`, and `Evening`. - -| Culture | File name | Resource name | Resource value | -|---------|-----------------------------|---------------|----------------| -| en-US | GreetingResources.txt | `Morning` | Good morning | -| en-US | GreetingResources.txt | `Afternoon` | Good afternoon | -| en-US | GreetingResources.txt | `Evening` | Good evening | -| fr-FR | GreetingResources.fr-FR.txt | `Morning` | Bonjour | -| fr-FR | GreetingResources.fr-FR.txt | `Afternoon` | Bonjour | -| fr-FR | GreetingResources.fr-FR.txt | `Evening` | Bonsoir | -| ru-RU | GreetingResources.ru-RU.txt | `Morning` | Доброе утро | -| ru-RU | GreetingResources.ru-RU.txt | `Afternoon` | Добрый день | -| ru-RU | GreetingResources.ru-RU.txt | `Evening` | Добрый вечер | - -You can use the following batch file to compile the Visual Basic example and create an executable named Greet.exe. To compile with C#, change the compiler name from `vbc` to `csc` and the file extension from `.vb` to `.cs`. - -``` -resgen GreetingResources.txt -vbc Greet.vb /resource: GreetingResources.resources - -md fr-FR -resgen GreetingResources.fr-FR.txt -al /out:fr-FR\Greet.resources.dll /culture:fr-FR /embed: GreetingResources.fr-FR.resources - -md ru-RU -resgen GreetingResources.ru-RU.txt -al /out:ru-RU\Greet.resources.dll /culture:ru-RU /embed: GreetingResources.ru-RU.resources -``` - -Here's the source code for the example (ShowDate.vb for the Visual Basic version or ShowDate.cs for the C# version of the code). - -:::code language="csharp" source="./snippets/System.Resources/ResourceManager/.ctor/csharp/greet.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/.ctor/vb/greet.vb" id="Snippet3"::: - -In addition to defining an app class named `Example`, the source code defines an internal class whose name, `GreetingResources`, is the same as the base name of the resource files. This makes it possible to successfully instantiate a object by calling the constructor. - -Notice that the output displays the appropriate localized string except when the current UI culture is Swedish (Sweden), in which case it uses English language resources. Because Swedish language resources are unavailable, the app uses the resources of the default culture, as defined by the attribute, instead. - -## constructor - -This section pertains to the constructor overload. - -### Desktop apps - -In desktop apps, the individual culture-specific resource files should be contained in satellite assemblies, and the default culture's resource file should be contained in the main assembly. A satellite assembly is assumed to contain resources for a single culture specified in that assembly's manifest, and is loaded as necessary. - -> [!NOTE] -> To retrieve resources from *.resources* files directly instead of retrieving them from assemblies, you must call the method instead to instantiate a object. - -If the resource file identified by `baseName` cannot be found in `assembly`, the method instantiates a object, but the attempt to retrieve a specific resource throws an exception, typically . For information about diagnosing the cause of the exception, see the "Handling the MissingManifestResourceException Exception" section of the class topic. - -### Windows 8.x apps - -> [!IMPORTANT] -> Although the class is supported in Windows 8.x apps, we do not recommend its use. Use this class only when you develop Portable Class Library projects that can be used with Windows 8.x apps. To retrieve resources from Windows 8.x apps, use the [Windows.ApplicationModel.Resources.ResourceLoader](/uwp/api/windows.applicationmodel.resources.resourceloader) class instead. - -In Windows 8.x apps, the resource manager uses the simple name of the `assembly` parameter to look up a matching resource set in the app's package resource index (PRI) file. The `baseName` parameter is used to look up a resource item within the resource set. For example, the root name for PortableLibrary1.Resource1.de-DE.resources is PortableLibrary1.Resource1. - -### Example - -The following example uses a simple non-localized "Hello World" app to illustrate the constructor. The contents of a text file named *ExampleResources.txt* is `Greeting=Hello`. When the app is compiled, the resource is embedded in the main app assembly. - -The text file can be converted to a binary resource file by using the [Resource File Generator (ResGen.exe)](../../framework/tools/resgen-exe-resource-file-generator.md) at the command prompt as follows: - -```cmd -resgen ExampleResources.txt -``` - -The following example provides the executable code that instantiates a object, prompts the user to enter a name, and displays a greeting. - -:::code language="csharp" source="./snippets/System.Resources/ResourceManager/.ctor/csharp/example.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/.ctor/vb/example.vb" id="Snippet1"::: - -It can be compiled by using the following command in C#: - -```cmd -csc Example.cs /resource:ExampleResources.resources -``` - -The example retrieves a reference to the assembly that contains the resource file by passing a type defined in that assembly to the `typeof` function (in C#) or the `GetType` function (in Visual Basic) and retrieving the value of its property. diff --git a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getobject.md b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getobject.md deleted file mode 100644 index 45c5a5973189e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getobject.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -title: System.Resources.ResourceManager.GetObject methods -description: Learn about the System.Resources.ResourceManager.GetObject methods. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - VB ---- -# System.Resources.ResourceManager.GetObject methods - -[!INCLUDE [context](includes/context.md)] - -The method is used to retrieve non-string resources. These include values that belong to primitive data types such as or , bitmaps (such as a object), or custom serialized objects. Typically, the returned object must be cast (in C#) or converted (in Visual Basic) to an object of the appropriate type. - -The property determines whether the comparison of `name` with the names of resources is case-insensitive or case-sensitive (the default). - -> [!NOTE] -> These methods can throw more exceptions than are listed. One reason this might occur is if a method that this method calls throws an exception. For example, a exception might be thrown if an error was made deploying or installing a satellite assembly, or a exception might be thrown if a user-defined type throws a user-defined exception when the type is deserialized. - -## method - -The returned resource is localized for the UI culture of the current thread, which is defined by the property. If the resource is not localized for that culture, the resource manager uses fallback rules to load an appropriate resource. If no usable set of localized resources is found, the falls back on the default culture's resources. If a resource set for the default culture is not found, the method throws a exception or, if the resource set is expected to reside in a satellite assembly, a exception. If the resource manager can load an appropriate resource set but cannot find a resource named `name`, the method returns `null`. - -### Example - -The following example uses the method to deserialize a custom object. The example includes a source code file named UIElements.cs (UIElements.vb if you're using Visual Basic) that defines the following structure named `PersonTable`. This structure is intended to be used by a general table display routine that displays the localized names of table columns. Note that the `PersonTable` structure is marked with the attribute. - -:::code language="csharp" source="./snippets/System.Resources/ResourceManager/Overview/csharp/example1.cs" id="Snippet6"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/GetObject/vb/example.vb" id="Snippet6"::: - -The following code from a file named CreateResources.cs (or CreateResources.vb for Visual Basic) creates an XML resource file named UIResources.resx that stores a table title and a `PersonTable` object that contains information for an app that is localized for the English language. - -:::code language="csharp" source="./snippets/System.Resources/ResourceManager/Overview/csharp/example11.cs" id="Snippet7"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/GetObject/vb/example.vb" id="Snippet7"::: - -The following code in a source code file named GetObject.cs (or GetObject.vb) then retrieves the resources and displays them to the console. - -:::code language="csharp" source="./snippets/System.Resources/ResourceManager/Overview/csharp/example2.cs" id="Snippet8"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/GetObject/vb/example2.vb" id="Snippet8"::: - -You can build the necessary resource file and assemblies and run the app by executing the following batch file. You must use the `/r` option to supply Resgen.exe with a reference to UIElements.dll so that it can access information about the `PersonTable` structure. If you're using C#, replace the `vbc` compiler name with `csc`, and replace the `.vb` extension with `.cs`. - -``` -vbc /t:library UIElements.vb -vbc CreateResources.vb /r:UIElements.dll -CreateResources - -resgen UIResources.resx /r:UIElements.dll -vbc GetObject.vb /r:UIElements.dll /resource:UIResources.resources - -GetObject.exe -``` - -## method - -The returned resource is localized for the culture that is specified by `culture`, or for the culture that is specified by the property if `culture` is `null`. If the resource is not localized for that culture, the resource manager uses fallback rules to load an appropriate resource. If no usable set of localized resources is found, the resource manager falls back on the default culture's resources. If a resource set for the default culture is not found, the method throws a exception or, if the resource set is expected to reside in a satellite assembly, a exception. If the resource manager can load an appropriate resource set but cannot find a resource named `name`, the method returns `null`. - -### Example - -The following example uses the method to deserialize a custom object. The example includes a source code file named NumberInfo.cs (NumberInfo.vb if you're using Visual Basic) that defines the following structure named `Numbers`. This structure is intended to be used by a simple educational app that teaches non-English speaking students to count to ten in English. Note that the `Numbers` class is marked with the attribute. - -:::code language="csharp" source="./snippets/System.Resources/ResourceManager/GetObject/csharp/numberinfo.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/GetObject/vb/numberinfo.vb" id="Snippet1"::: - -The following source code from a file named CreateResources.cs (CreateResources.vb for Visual Basic) creates XML resource files for the default English language, as well as for the French, Portuguese, and Russian languages. - -:::code language="csharp" source="./snippets/System.Resources/ResourceManager/GetObject/csharp/createresources.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/GetObject/vb/createresources.vb" id="Snippet2"::: - -The resources are consumed by the following app, which sets the current UI culture to French (France), Portuguese (Brazil), or Russian (Russia). It calls the method to get a `Numbers` object that contains localized numbers and the method to get a `Numbers` object that contains English language numbers. It then displays odd numbers using the current UI culture and the English language. The source code file is named ShowNumbers.cs (ShowNumbers.vb). - -:::code language="csharp" source="./snippets/System.Resources/ResourceManager/GetObject/csharp/shownumbers.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/GetObject/vb/shownumbers.vb" id="Snippet3"::: - -You can use the following batch file to build and execute the Visual Basic version of the example. If you're using C#, replace `vbc` with `csc`, and replace the `.vb` extension with `.cs`. - -``` -vbc /t:library NumberInfo.vb - -vbc CreateResources.vb /r:NumberInfo.dll -CreateResources - -resgen NumberResources.resx /r:NumberInfo.dll - -resgen NumberResources.fr.resx /r:Numberinfo.dll -Md fr -al /embed:NumberResources.fr.resources /culture:fr /t:lib /out:fr\ShowNumbers.resources.dll - -resgen NumberResources.pt.resx /r:Numberinfo.dll -Md pt -al /embed:NumberResources.pt.resources /culture:pt /t:lib /out:pt\ShowNumbers.resources.dll - -resgen NumberResources.ru.resx /r:Numberinfo.dll -Md ru -al /embed:NumberResources.ru.resources /culture:ru /t:lib /out:ru\ShowNumbers.resources.dll - -vbc ShowNumbers.vb /r:NumberInfo.dll /resource:NumberResources.resources -ShowNumbers.exe -``` - -## Performance considerations - -If you call the method multiple times with the same `name` parameter, do not depend on the method returning a reference to the same object with each call. This is because the method can return a reference to an existing resource object in a cache, or it can reload the resource and return a reference to a new resource object. diff --git a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getstring.md b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getstring.md deleted file mode 100644 index 6226b2f69169a..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager-getstring.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: System.Resources.ResourceManager.GetString methods -description: Learn about the System.Resources.ResourceManager.GetString methods. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - VB ---- -# System.Resources.ResourceManager.GetString methods - -[!INCLUDE [context](includes/context.md)] - -The property determines whether the comparison of `name` with the names of resources is case-insensitive (the default) or case-sensitive. - -> [!NOTE] -> The methods can throw more exceptions than are listed. One reason this might occur is if a method that this method calls throws an exception. For example, a exception might be thrown if an error was made deploying or installing a satellite assembly, or a exception might be thrown if a user-defined type throws a user-defined exception when the type is deserialized. - -## method - -### Desktop apps - -In desktop apps, the resource that is returned is localized for the UI culture of the current thread, as defined by the property. If the resource has not been localized for that culture, the resource manager probes for a resource by following the steps outlined in the "Resource Fallback Process" section of the [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps) article. If no usable set of localized resources is found, the resource manager falls back on the default culture's resources. If the resource manager cannot load the default culture's resource set, the method throws a exception or, if the resource set is expected to reside in a satellite assembly, a exception. If the resource manager can load an appropriate resource set but cannot find a resource named `name`, the method returns `null`. - -### Windows 8.x apps - -> [!IMPORTANT] -> Although the class is supported in Windows 8.x apps, we do not recommend its use. Use this class only when you develop Portable Class Library projects that can be used with Windows 8.x apps. To retrieve resources from Windows 8.x apps, use the [Windows.ApplicationModel.Resources.ResourceLoader](/uwp/api/windows.applicationmodel.resources.resourceloader) class instead. - -In Windows 8.x apps, the method returns the value of the `name` string resource, localized for the caller's current UI culture settings. The list of cultures is derived from the operating system's preferred UI language list. If the resource manager cannot match `name`, the method returns `null`. - -### Example - -The following example uses the method to retrieve culture-specific resources. It consists of resources compiled from .txt files for the English (en), French (France) (fr-FR), and Russian (Russia) (ru-RU) cultures. The example changes the current culture and current UI culture to English (United States), French (France), Russian (Russia), and Swedish (Sweden). It then calls the method to retrieve the localized string, which it displays along with the current day and month. Notice that the output displays the appropriate localized string except when the current UI culture is Swedish (Sweden). Because Swedish language resources are unavailable, the app instead uses the resources of the default culture, which is English. The example requires the text-based resource files listed in following table. Each has a single string resource named `DateStart`. - -| Culture | File name | Resource name | Resource value | -|---------|-----------------------|---------------|-----------------------| -| en-US | DateStrings.txt | `DateStart` | Today is | -| fr-FR | DateStrings.fr-FR.txt | `DateStart` | Aujourd'hui, c'est le | -| ru-RU | DateStrings.ru-RU.txt | `DateStart` | Сегодня | - -You can use the following batch file to compile the C# example. For Visual Basic, change `csc` to `vbc`, and change the extension of the source code file from `.cs` to `.vb`. - -``` -resgen DateStrings.txt -csc showdate.cs /resource:DateStrings.resources - -md fr-FR -resgen DateStrings.fr-FR.txt -al /out:fr-FR\Showdate.resources.dll /culture:fr-FR /embed:DateStrings.fr-FR.resources - -md ru-RU -resgen DateStrings.ru-RU.txt -al /out:ru-RU\Showdate.resources.dll /culture:ru-RU /embed:DateStrings.ru-RU.resources -``` - -Here's the source code for the example (ShowDate.vb for the Visual Basic version or ShowDate.cs for the C# version). - -:::code language="csharp" source="./snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate1.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/GetString/vb/showdate.vb" id="Snippet2"::: - -## method - -### Desktop apps - -In desktop apps, if `culture` is `null`, the method uses the current UI culture obtained from the property. - -The resource that is returned is localized for the culture specified by the `culture` parameter. If the resource has not been localized for `culture`, the resource manager probes for a resource by following the steps outlined in the "Resource Fallback Process" section of the [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps) topic. If no usable set of resources is found, the resource manager falls back on the default culture's resources. If the resource manager cannot load the default culture's resource set, the method throws a exception or, if the resource set is expected to reside in a satellite assembly, a exception. If the resource manager can load an appropriate resource set but cannot find a resource named `name`, the method returns `null`. - -### Windows 8.x apps - -> [!IMPORTANT] -> Although the class is supported in Windows 8.x apps, we do not recommend its use. Use this class only when you develop Portable Class Library projects that can be used with Windows 8.x apps. To retrieve resources from Windows 8.x apps, use the [Windows.ApplicationModel.Resources.ResourceLoader](/uwp/api/windows.applicationmodel.resources.resourceloader) class instead. - -In Windows 8.x apps, the method returns the value of the `name` string resource, localized for the culture specified by the `culture` parameter. If the resource is not localized for the `culture` culture, the lookup uses the entire Windows 8 language fallback list, and stops after looking in the default culture. If the resource manager cannot match `name`, the method returns `null`. - -### Example - -The following example uses the method to retrieve culture-specific resources. The example's default culture is English (en), and it includes satellite assemblies for the French (France) (fr-FR) and Russian (Russia) (ru-RU) cultures. The example changes the current culture and current UI culture to Russian (Russia) before calling . It then calls the method and the method and passes objects that represent the French (France) and Swedish (Sweden) cultures to each method. In the output, the month and day of the month as well as the string that precedes them appear in French, because the method is able to retrieve the French language resource. However, when the Swedish (Sweden) culture is used, the month and day of the month appear in Swedish, although the string that precedes them is in English. This is because the resource manager cannot find localized Swedish language resources, so it returns a resource for the default English culture instead. - -The example requires the text-based resource files listed in following table. Each has a single string resource named `DateStart`. - -| Culture | File name | Resource name | Resource value | -|---------|-----------------------|---------------|-----------------------| -| en-US | DateStrings.txt | `DateStart` | Today is | -| fr-FR | DateStrings.fr-FR.txt | `DateStart` | Aujourd'hui, c'est le | -| ru-RU | DateStrings.ru-RU.txt | `DateStart` | Сегодня | - -You can use the following batch file to compile the Visual Basic example. To compile in C#, change `vbc` to `csc`, and change the extension of the source code file from `.vb` to `.cs`. - -``` -resgen DateStrings.txt -vbc showdate.vb /resource:DateStrings.resources - -md fr-FR -resgen DateStrings.fr-FR.txt -al /out:fr-FR\Showdate.resources.dll /culture:fr-FR /embed:DateStrings.fr-FR.resources - -md ru-RU -resgen DateStrings.ru-RU.txt -al /out:ru-RU\Showdate.resources.dll /culture:ru-RU /embed:DateStrings.ru-RU.resources -``` - -Here's the source code for the example (ShowDate.vb for the Visual Basic version or ShowDate.cs for the C# version). - -:::code language="csharp" source="./snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate2.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/GetString/vb/showdate2.vb" id="Snippet3"::: diff --git a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md b/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md deleted file mode 100644 index 07e7de5e10afd..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-resources-resourcemanager.md +++ /dev/null @@ -1,308 +0,0 @@ ---- -title: System.Resources.ResourceManager class -description: Learn more about the System.Resources.ResourceManager class through these supplemental API remarks. -ms.date: 01/02/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Resources.ResourceManager class - -[!INCLUDE [context](includes/context.md)] - -[!INCLUDE [untrusted-data-class-note](./includes/untrusted-data-class-note.md)] - -The class retrieves resources from a binary .resources file that is embedded in an assembly or from a standalone .resources file. If an app has been localized and localized resources have been deployed in [satellite assemblies](/dotnet/framework/resources/creating-satellite-assemblies-for-desktop-apps), it looks up culture-specific resources, provides resource fallback when a localized resource does not exist, and supports resource serialization. - -## Desktop apps - -For desktop apps, the class retrieves resources from binary resource (.resources) files. Typically, a language compiler or the [Assembly Linker (AL.exe)](../../framework/tools/al-exe-assembly-linker.md) embeds these resource files in an assembly. You can also use a object to retrieve resources directly from a .resources file that is not embedded in an assembly, by calling the method. - -> [!CAUTION] -> Using standalone .resources files in an ASP.NET app will break XCOPY deployment, because the resources remain locked until they are explicitly released by the method. If you want to deploy resources with your ASP.NET apps, you should compile your .resources files into satellite assemblies. - -In a resource-based app, one .resources file contains the resources of the default culture whose resources are used if no culture-specific resources can be found. For example, if an app's default culture is English (en), the English language resources are used whenever localized resources cannot be found for a specific culture, such as English (United States) (en-US) or French (France) (fr-FR). Typically, the resources for the default culture are embedded in the main app assembly, and resources for other localized cultures are embedded in satellite assemblies. Satellite assemblies contain only resources. They have the same root file name as the main assembly and an extension of .resources.dll. For apps whose assemblies are not registered in the global assembly cache, satellite assemblies are stored in an app subdirectory whose name corresponds to the assembly's culture. - -### Create resources - -When you develop a resource-based app, you store resource information in text files (files that have a .txt or .restext extension) or XML files (files that have a .resx extension). You then compile the text or XML files with the [Resource File Generator (Resgen.exe)](../../framework/tools/resgen-exe-resource-file-generator.md) to create a binary .resources file. You can then embed the resulting .resources file in an executable or library by using a compiler option such as `/resources` for the C# and Visual Basic compilers, or you can embed it in a satellite assembly by using the [Assembly Linker (AI.exe)](../../framework/tools/al-exe-assembly-linker.md). If you include a .resx file in your Visual Studio project, Visual Studio handles the compilation and embedding of default and localized resources automatically as part of the build process. - -Ideally, you should create resources for every language your app supports, or at least for a meaningful subset of each language. The binary .resources file names follow the naming convention *basename*.*cultureName*.resources, where *basename* is the name of the app or the name of a class, depending on the level of detail you want. The property is used to determine *cultureName*. A resource for the app's default culture should be named *basename*.resources. - -For example, suppose that an assembly has several resources in a resource file that has the base name MyResources. These resource files should have names such as MyResources.ja-JP.resources for the Japan (Japanese) culture, MyResources.de.resources for the German culture, MyResources.zh-CHS.resources for the simplified Chinese culture, and MyResources.fr-BE.resources for the French (Belgium) culture. The default resource file should be named MyResources.resources. The culture-specific resource files are commonly packaged in satellite assemblies for each culture. The default resource file should be embedded in the app's main assembly. - -Note that [Assembly Linker](../../framework/tools/al-exe-assembly-linker.md) allows resources to be marked as private, but you should always mark them as public so they can be accessed by other assemblies. (Because a satellite assembly contains no code, resources that are marked as private are unavailable to your app through any mechanism.) - -For more information about creating, packaging, and deploying resources, see the articles [Creating Resource Files](/dotnet/framework/resources/creating-resource-files-for-desktop-apps), [Creating Satellite Assemblies](/dotnet/framework/resources/creating-satellite-assemblies-for-desktop-apps), and [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps). - -### Instantiate a ResourceManager object - -You instantiate a object that retrieves resources from an embedded .resources file by calling one of its class constructor overloads. This tightly couples a object with a particular .resources file and with any associated localized .resources files in satellite assemblies. - -The two most commonly called constructors are: - -- looks up resources based on two pieces of information that you supply: the base name of the .resources file, and the assembly in which the default .resources file resides. The base name includes the namespace and root name of the .resources file, without its culture or extension. Note that .resources files that are compiled from the command line typically do not include a namespace name, whereas .resources files that are created in the Visual Studio environment do. For example, if a resource file is named MyCompany.StringResources.resources and the constructor is called from a static method named `Example.Main`, the following code instantiates a object that can retrieve resources from the .resources file: - - :::code language="csharp" source="./snippets/System.Resources/ResourceManager/Overview/csharp/ctor1.cs" id="Snippet1"::: - :::code language="vb" source="./snippets/System.Resources/ResourceManager/Overview/vb/ctor1.vb" id="Snippet1"::: - -- looks up resources in satellite assemblies based on information from a type object. The type's fully qualified name corresponds to the base name of the .resources file without its file name extension. In desktop apps that are created by using the Visual Studio Resource Designer, Visual Studio creates a wrapper class whose fully qualified name is the same as the root name of the .resources file. For example, if a resource file is named MyCompany.StringResources.resources and there is a wrapper class named `MyCompany.StringResources`, the following code instantiates a object that can retrieve resources from the .resources file: - - :::code language="csharp" source="./snippets/System.Resources/ResourceManager/Overview/csharp/ctor1.cs" id="Snippet2"::: - :::code language="vb" source="./snippets/System.Resources/ResourceManager/Overview/vb/ctor1.vb" id="Snippet2"::: - -If the appropriate resources cannot be found, the constructor call creates a valid object. However, the attempt to retrieve a resource throws a exception. For information about dealing with the exception, see the [Handle MissingManifestResourceException and MissingSatelliteAssemblyException Exceptions](#handle-missingmanifestresourceexception-and-missingsatelliteassemblyexception-exceptions) section later in this article. - -The following example shows how to instantiate a object. It contains the source code for an executable named ShowTime.exe. It also includes the following text file named Strings.txt that contains a single string resource, `TimeHeader`: - -``` -TimeHeader=The current time is -``` - -You can use a batch file to generate the resource file and embed it into the executable. Here's the batch file to generate an executable by using the C# compiler: - -``` -resgen strings.txt -csc ShowTime.cs /resource:strings.resources -``` - -For the Visual Basic compiler, you can use the following batch file: - -``` -resgen strings.txt -vbc ShowTime.vb /resource:strings.resources -``` - -:::code language="csharp" source="./snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showtime.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/Overview/vb/showtime.vb" id="Snippet1"::: - -### ResourceManager and culture-specific resources - -A localized app requires resources to be deployed, as discussed in the article [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps). If the assemblies are properly configured, the resource manager determines which resources to retrieve based on the current thread's property. (That property also returns the current thread's UI culture.) For example, if an app is compiled with default English language resources in the main assembly and with French and Russian language resources in two satellite assemblies, and the property is set to fr-FR, the resource manager retrieves the French resources. - -You can set the property explicitly or implicitly. The way you set it determines how the object retrieves resources based on culture: - -- If you explicitly set the property to a specific culture, the resource manager always retrieves the resources for that culture, regardless of the user's browser or operating system language. Consider an app that is compiled with default English language resources and three satellite assemblies that contain resources for English (United States), French (France), and Russian (Russia). If the property is set to fr-FR, the object always retrieves the French (France) resources, even if the user's operating system language is not French. Make sure that this is the desired behavior before you set the property explicitly. - - In ASP.NET apps, you must set the property explicitly, because it is unlikely that the setting on the server will match incoming client requests. An ASP.NET app can set the property explicitly to the user's browser accept language. - - Explicitly setting the property defines the current UI culture for that thread. It does not affect the current UI culture of any other threads in an app. - -- You can set the UI culture of all threads in an app domain by assigning a object that represents that culture to the static property. - -- If you do not explicitly set the current UI culture and you do not define a default culture for the current app domain, the property is set implicitly by the Windows `GetUserDefaultUILanguage` function. This function is provided by the Multilingual User Interface (MUI), which enables the user to set the default language. If the UI language is not set by the user, it defaults to the system-installed language, which is the language of operating system resources. - -The following simple "Hello world" example sets the current UI culture explicitly. It contains resources for three cultures: English (United States) or en-US, French (France) or fr-FR, and Russian (Russia) or ru-RU. The en-US resources are contained in a text file named Greetings.txt: - -``` -HelloString=Hello world! -``` - -The fr-FR resources are contained in a text file named Greetings.fr-FR.txt: - -``` -HelloString=Salut tout le monde! -``` - -The ru-RU resources are contained in a text file named Greetings.ru-RU.txt: - -``` -HelloString=Всем привет! -``` - -Here's the source code for the example (Example.vb for the Visual Basic version or Example.cs for the C# version): - -:::code language="csharp" source="./snippets/System.Resources/ResourceManager/Overview/csharp/example.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Resources/CurrentCulture/Overview/vb/example.vb" id="Snippet1"::: - -To compile this example, create a batch (.bat) file that contains the following commands and run it from the command prompt. If you're using C#, specify `csc` instead of `vbc` and `Example.cs` instead of `Example.vb`. - -``` -resgen Greetings.txt -vbc Example.vb /resource:Greetings.resources - -resgen Greetings.fr-FR.txt -Md fr-FR -al /embed:Greetings.fr-FR.resources /culture:fr-FR /out:fr-FR\Example.resources.dll - -resgen Greetings.ru-RU.txt -Md ru-RU -al /embed:Greetings.ru-RU.resources /culture:ru-RU /out:ru-RU\Example.resources.dll -``` - -### Retrieve resources - -You call the and methods to access a specific resource. You can also call the method to retrieve non-string resources as a byte array. By default, in an app that has localized resources, these methods return the resource for the culture determined by the current UI culture of the thread that made the call. See the previous section, [ResourceManager and culture-specific resources](#resourcemanager-and-culture-specific-resources), for more information about how the current UI culture of a thread is defined. If the resource manager cannot find the resource for the current thread's UI culture, it uses a fallback process to retrieve the specified resource. If the resource manager cannot find any localized resources, it uses the resources of the default culture. For more information about resource fallback rules, see the "Resource Fallback Process" section of the article [Packaging and Deploying Resources](/dotnet/framework/resources/packaging-and-deploying-resources-in-desktop-apps). - -> [!NOTE] -> If the .resources file specified in the class constructor cannot be found, the attempt to retrieve a resource throws a or exception. For information about dealing with the exception, see the [Handle MissingManifestResourceException and MissingSatelliteAssemblyException Exceptions](#handle-missingmanifestresourceexception-and-missingsatelliteassemblyexception-exceptions) section later in this article. - -The following example uses the method to retrieve culture-specific resources. It consists of resources compiled from .txt files for the English (en), French (France) (fr-FR), and Russian (Russia) (ru-RU) cultures. The example changes the current culture and current UI culture to English (United States), French (France), Russian (Russia), and Swedish (Sweden). It then calls the method to retrieve the localized string, which it displays along with the current day and month. Notice that the output displays the appropriate localized string except when the current UI culture is Swedish (Sweden). Because Swedish language resources are unavailable, the app instead uses the resources of the default culture, which is English. - -The example requires the text-based resource files listed in following table. Each has a single string resource named `DateStart`. - -| Culture | File name | Resource name | Resource value | -|---------|-----------------------|---------------|-----------------------| -| en-US | DateStrings.txt | `DateStart` | Today is | -| fr-FR | DateStrings.fr-FR.txt | `DateStart` | Aujourd'hui, c'est le | -| ru-RU | DateStrings.ru-RU.txt | `DateStart` | Сегодня | - -Here's the source code for the example (ShowDate.vb for the Visual Basic version or ShowDate.cs for the C# version of the code). - -:::code language="csharp" source="./snippets/System.Resources/MissingManifestResourceException/Overview/csharp/showdate.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Resources/ResourceManager/Overview/vb/showdate.vb" id="Snippet2"::: - -To compile this example, create a batch file that contains the following commands and run it from the command prompt. If you're using C#, specify `csc` instead of `vbc` and `showdate.cs` instead of `showdate.vb`. - -``` -resgen DateStrings.txt -vbc showdate.vb /resource:DateStrings.resources - -md fr-FR -resgen DateStrings.fr-FR.txt -al /out:fr-FR\Showdate.resources.dll /culture:fr-FR /embed:DateStrings.fr-FR.resources - -md ru-RU -resgen DateStrings.ru-RU.txt -al /out:ru-RU\Showdate.resources.dll /culture:ru-RU /embed:DateStrings.ru-RU.resources -``` - -There are two ways to retrieve the resources of a specific culture other than the current UI culture: - -- You can call the , , or method to retrieve a resource for a specific culture. If a localized resource cannot be found, the resource manager uses the resource fallback process to locate an appropriate resource. -- You can call the method to obtain a object that represents the resources for a particular culture. In the method call, you can determine whether the resource manager probes for parent cultures if it is unable to find localized resources, or whether it simply falls back to the resources of the default culture. You can then use the methods to access the resources (localized for that culture) by name, or to enumerate the resources in the set. - -### Handle MissingManifestResourceException and MissingSatelliteAssemblyException exceptions - -If you try to retrieve a specific resource, but the resource manager cannot find that resource and either no default culture has been defined or the resources of the default culture cannot be located, the resource manager throws a exception if it expects to find the resources in the main assembly or a if it expects to find the resources in a satellite assembly. Note that the exception is thrown when you call a resource retrieval method such as or , and not when you instantiate a object. - -The exception is typically thrown under the following conditions: - -- The appropriate resource file or satellite assembly does not exist. If the resource manager expects the app's default resources to be embedded in the main app assembly, they are absent. If the attribute indicates that the app's default resources reside in a satellite assembly, that assembly cannot be found. When you compile your app, make sure that resources are embedded in the main assembly or that the necessary satellite assembly is generated and is named appropriately. Its name should take the form *appName*.resources.dll, and it should be located in a directory named after the culture whose resources it contains. - -- Your app doesn't have a default or neutral culture defined. Add the attribute to a source code file or to the project information file (AssemblyInfo.vb for a Visual Basic app or AssemblyInfo.cs for a C# app) file. - -- The `baseName` parameter in the constructor does not specify the name of a .resources file. The name should include the resource file's fully qualified namespace but not its file name extension. Typically, resource files that are created in Visual Studio include namespace names, but resource files that are created and compiled at the command prompt do not. You can determine the names of embedded .resources files by compiling and running the following utility. This is a console app that accepts the name of a main assembly or satellite assembly as a command-line parameter. It displays the strings that should be provided as the `baseName` parameter so that the resource manager can correctly identify the resource. - - :::code language="csharp" source="./snippets/System.Resources/MissingManifestResourceException/Overview/csharp/resourcenames.cs" id="Snippet4"::: - :::code language="vb" source="./snippets/System.Resources/MissingManifestResourceException/Overview/vb/resourcenames.vb" id="Snippet4"::: - -If you are changing the current culture of your application explicitly, you should also remember that the resource manager retrieves a resource set based on the value of the property, and not the property. Typically, if you change one value, you should also change the other. - -### Resource versioning - -Because the main assembly that contains an app's default resources is separate from the app's satellite assemblies, you can release a new version of your main assembly without redeploying the satellite assemblies. You use the attribute to use existing satellite assemblies and instruct the resource manager not to redeploy them with a new version of your main assembly, - -For more information about versioning support for satellite assemblies, see the article [Retrieving Resources](/dotnet/framework/resources/retrieving-resources-in-desktop-apps). - -### `` configuration file node - -> [!NOTE] -> This section is specific to .NET Framework apps. - -For executables that are deployed and run from a website (HREF .exe files), the object may probe for satellite assemblies over the web, which can hurt your app's performance. To eliminate the performance problem, you can limit this probing to the satellite assemblies that you have deployed with your app. To do this, you create a `` node in your app's configuration file to specify that you have deployed a specific set of cultures for your app, and that the object should not try to probe for any culture that is not listed in that node. - -> [!NOTE] -> The preferred alternative to creating a `` node is to use the [ClickOnce Deployment Manifest](/visualstudio/deployment/clickonce-deployment-manifest) feature. - -In your app's configuration file, create a section similar to the following: - -```xml - - - - - cultureName1 - cultureName2 - cultureName3 - - - -``` - -Edit this configuration information as follows: - -- Specify one or more `` nodes for each main assembly that you deploy, where each node specifies a fully qualified assembly name. Specify the name of your main assembly in place of *MainAssemblyName*, and specify the `Version`, `PublicKeyToken`, and `Culture` attribute values that correspond to your main assembly. - - For the `Version` attribute, specify the version number of your assembly. For example, the first release of your assembly might be version number 1.0.0.0. - - For the `PublicKeyToken` attribute, specify the keyword `null` if you have not signed your assembly with a strong name, or specify your public key token if you have signed your assembly. - - For the `Culture` attribute, specify the keyword `neutral` to designate the main assembly and cause the class to probe only for the cultures listed in the `` nodes. - - For more information about fully qualified assembly names, see the article [Assembly Names](../../standard/assembly/names.md). For more information about strong-named assemblies, see the article [Create and use strong-named assemblies](../../standard/assembly/create-use-strong-named.md). - -- Specify one or more `` nodes with a specific culture name, such as "fr-FR", or a neutral culture name, such as "fr". - -If resources are needed for any assembly not listed under the `` node, the class probes for cultures using standard probing rules. - -## Windows 8.x apps - -> [!IMPORTANT] -> Although the class is supported in Windows 8.x apps, we do not recommend its use. Use this class only when you develop Portable Class Library projects that can be used with Windows 8.x apps. To retrieve resources from Windows 8.x apps, use the [Windows.ApplicationModel.Resources.ResourceLoader](/uwp/api/Windows.ApplicationModel.Resources.ResourceLoader) class instead. - -For Windows 8.x apps, the class retrieves resources from package resource index (PRI) files. A single PRI file (the application package PRI file) contains the resources for both the default culture and any localized cultures. You use the MakePRI utility to create a PRI file from one or more resource files that are in XML resource (.resw) format. For resources that are included in a Visual Studio project, Visual Studio handles the process of creating and packaging the PRI file automatically. You can then use the .NET class to access the app's or library's resources. - -You can instantiate a object for a Windows 8.x app in the same way that you do for a desktop app. - -You can then access the resources for a particular culture by passing the name of the resource to be retrieved to the method. By default, this method returns the resource for the culture determined by the current UI culture of the thread that made the call. You can also retrieve the resources for a specific culture by passing the name of the resource and a object that represents the culture whose resource is to be retrieved to the method. If the resource for the current UI culture or the specified culture cannot be found, the resource manager uses a UI language fallback list to locate a suitable resource. - -## Examples - -The following example demonstrates how to use an explicit culture and the implicit current UI culture to obtain string resources from a main assembly and a satellite assembly. For more information, see the "Directory Locations for Satellite Assemblies Not Installed in the Global Assembly Cache" section of the [Creating Satellite Assemblies](/dotnet/framework/resources/creating-satellite-assemblies-for-desktop-apps) topic. - -To run this example: - -1. In the app directory, create a file named rmc.txt that contains the following resource strings: - - ``` - day=Friday - year=2006 - holiday="Cinco de Mayo" - ``` - -2. Use the [Resource File Generator](../../framework/tools/resgen-exe-resource-file-generator.md) to generate the rmc.resources resource file from the rmc.txt input file as follows: - - ``` - resgen rmc.txt - ``` - -3. Create a subdirectory of the app directory and name it "es-MX". This is the culture name of the satellite assembly that you will create in the next three steps. - -4. Create a file named rmc.es-MX.txt in the es-MX directory that contains the following resource strings: - - ``` - day=Viernes - year=2006 - holiday="Cinco de Mayo" - ``` - -5. Use the [Resource File Generator](../../framework/tools/resgen-exe-resource-file-generator.md) to generate the rmc.es-MX.resources resource file from the rmc.es-MX.txt input file as follows: - - ``` - resgen rmc.es-MX.txt - ``` - -6. Assume that the filename for this example is rmc.vb or rmc.cs. Copy the following source code into a file. Then compile it and embed the main assembly resource file, rmc.resources, in the executable assembly. If you are using the Visual Basic compiler, the syntax is: - - ``` - vbc rmc.vb /resource:rmc.resources - ``` - - The corresponding syntax for the C# compiler is: - - ``` - csc /resource:rmc.resources rmc.cs - ``` - -7. Use the [Assembly Linker](../../framework/tools/al-exe-assembly-linker.md) to create a satellite assembly. If the base name of the app is rmc, the satellite assembly name must be rmc.resources.dll. The satellite assembly should be created in the es-MX directory. If es-MX is the current directory, use this command: - - ``` - al /embed:rmc.es-MX.resources /c:es-MX /out:rmc.resources.dll - ``` - -8. Run rmc.exe to obtain and display the embedded resource strings. - - :::code language="csharp" source="./snippets/System.Resources/ResourceManager/Overview/csharp/rmc.cs" id="Snippet1"::: - :::code language="vb" source="./snippets/System.Resources/ResourceManager/Overview/vb/rmc.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-resources-resourcereader.md b/docs/fundamentals/runtime-libraries/system-resources-resourcereader.md deleted file mode 100644 index 12986cb01b4d9..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-resources-resourcereader.md +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: System.Resources.ResourceReader class -description: Learn about the System.Resources.ResourceReader class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Resources.ResourceReader class - -[!INCLUDE [context](includes/context.md)] - -[!INCLUDE [untrusted-data-class-note](./includes/untrusted-data-class-note.md)] - -The class provides a standard implementation of the interface. A instance represents either a standalone .resources file or a .resources file that is embedded in an assembly. It is used to enumerate the resources in a .resources file and retrieve its name/value pairs. It differs from the class, which is used to retrieve specified named resources from a .resources file that is embedded in an assembly. The class is used to retrieve resources whose names are known in advance, whereas the class is useful for retrieving resources whose number or precise names are not known at compile time. For example, an application may use a resources file to store configuration information that is organized into sections and items in a section, where the number of sections or items in a section is not known in advance. Resources can then be named generically (such as `Section1`, `Section1Item1`, `Section1Item2`, and so on) and retrieved by using a object. - -> [!IMPORTANT] -> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface documentation. - -## Instantiate a ResourceReader object - -A .resources file is a binary file that has been compiled from either a text file or an XML .resx file by [Resgen.exe (Resource File Generator)](../../framework/tools/resgen-exe-resource-file-generator.md). A object can represent either a standalone .resources file or a .resources file that has been embedded in an assembly. - -To instantiate a object that reads from a standalone .resources file, use the class constructor with either an input stream or a string that contains the .resources file name. The following example illustrates both approaches. The first instantiates a object that represents a .resources file named `Resources1.resources` by using its file name. The second instantiates a object that represents a .resources file named `Resources2.resources` by using a stream created from the file. - -:::code language="csharp" source="./snippets/System.Resources/ResourceReader/Overview/csharp/ctor1.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Resources/ResourceReader/Overview/vb/ctor1.vb" id="Snippet2"::: - -To create a object that represents an embedded .resources file, instantiate an object from the assembly in which the .resources file is embedded. Its method returns a object that can be passed to the constructor. The following example instantiates a object that represents an embedded .resources file. - -:::code language="csharp" source="./snippets/System.Resources/ResourceReader/Overview/csharp/ctor1.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Resources/ResourceReader/Overview/vb/ctor1.vb" id="Snippet3"::: - -## Enumerate a ResourceReader object's resources - -To enumerate the resources in a .resources file, you call the method, which returns an object. You call the `IDictionaryEnumerator.MoveNext` method to move from one resource to the next. The method returns `false` when all the resources in the .resources file have been enumerated. - -> [!NOTE] -> Although the class implements the interface and the method, the method does not provide the implementation. Instead, the method returns an interface object that provides access to each resource's name/value pair. - -You can retrieve the individual resources in the collection in two ways: - -- You can iterate each resource in the collection and use properties to retrieve the resource name and value. We recommend this technique when all the resources are of the same type, or you know the data type of each resource. - -- You can retrieve the name of each resource when you iterate the collection and call the method to retrieve the resource's data. We recommend this approach when you do not know the data type of each resource or if the previous approach throws exceptions. - -### Retrieve resources by using IDictionaryEnumerator properties - -The first method of enumerating the resources in a .resources file involves directly retrieving each resource's name/value pair. After you call the `IDictionaryEnumerator.MoveNext` method to move to each resource in the collection, you can retrieve the resource name from the property and the resource data from the property. - -The following example shows how to retrieve the name and value of each resource in a .resources file by using the and properties. To run the example, create the following text file named ApplicationResources.txt to define string resources. - -``` -Title="Contact Information" -Label1="First Name:" -Label2="Middle Name:" -Label3="Last Name:" -Label4="SSN:" -Label5="Street Address:" -Label6="City:" -Label7="State:" -Label8="Zip Code:" -Label9="Home Phone:" -Label10="Business Phone:" -Label11="Mobile Phone:" -Label12="Other Phone:" -Label13="Fax:" -Label14="Email Address:" -Label15="Alternate Email Address:" -``` - -You can then convert the text resource file to a binary file named ApplicationResources.resources by using the following command: - -`resgen ApplicationResources.txt` - -The following example then uses the class to enumerate each resource in the standalone binary .resources file and to display its key name and corresponding value. - -:::code language="csharp" source="./snippets/System.Resources/ResourceReader/Overview/csharp/class1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Resources/ResourceReader/Overview/vb/class1.vb" id="Snippet1"::: - -The attempt to retrieve resource data from the property can throw the following exceptions: - -- A if the data is not in the expected format. -- A if the assembly that contains the type to which the data belongs cannot be found. -- A if the type to which the data belongs cannot be cannot be found. - -Typically, these exceptions are thrown if the .resources file has been modified manually, if the assembly in which a type is defined has either not been included with an application or has been inadvertently deleted, or if the assembly is an older version that predates a type. If one of these exceptions is thrown, you can retrieve resources by enumerating each resource and calling the method, as the following section shows. This approach provides you with some information about the data type that the property attempted to return. - -### Retrieve resources by name with GetResourceData - -The second approach to enumerating resources in a .resources file also involves navigating through the resources in the file by calling the `IDictionaryEnumerator.MoveNext` method. For each resource, you retrieve the resource's name from the property, which is then passed to the method to retrieve the resource's data. This is returned as a byte array in the `resourceData` argument. - -This approach is more awkward than retrieving the resource name and value from the and properties, because it returns the actual bytes that form the resource value. However, if the attempt to retrieve the resource throws an exception, the method can help identify the source of the exception by supplying information about the resource's data type. For more information about the string that indicates the resource's data type, see . - -The following example illustrates how to use this approach to retrieve resources and to handle any exceptions that are thrown. It programmatically creates a binary .resources file that contains four strings, one Boolean, one integer, and one bitmap. To run the example, do the following: - -1. Compile and execute the following source code, which creates a .resources file named ContactResources.resources. - - :::code language="csharp" source="./snippets/System.Resources/ResourceReader/Overview/csharp/createresourceex1.cs" id="Snippet5"::: - - The source code file is named CreateResources.cs. You can compile it in C# by using the following command: - - ``` - csc CreateResources.cs /r:library.dll - ``` - -2. Compile and run the following code to enumerate the resources in the ContactResources.resources file. - - :::code language="csharp" source="./snippets/System.Resources/ResourceReader/Overview/csharp/readresourceex1.cs" id="Snippet6"::: - - After modifying the source code (for example, by deliberately throwing a at the end of the `try` block), you can run the example to see how calls to enable you to retrieve or recreate some resource information. diff --git a/docs/fundamentals/runtime-libraries/system-resources-satellitecontractversionattribute.md b/docs/fundamentals/runtime-libraries/system-resources-satellitecontractversionattribute.md deleted file mode 100644 index 2766876648f52..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-resources-satellitecontractversionattribute.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -title: System.Resources.SatelliteContractVersionAttribute class -description: Learn about the System.Resources.SatelliteContractVersionAttribute class. -ms.date: 12/31/2023 ---- -# System.Resources.SatelliteContractVersionAttribute class - -[!INCLUDE [context](includes/context.md)] - -In desktop apps, the attribute establishes a contract between a main assembly and all its satellites. You apply this attribute to your main assembly, and pass it the version number of the satellite assemblies that will work with this version of the main assembly. When the resource manager ( object) looks up resources, it explicitly loads the satellite version specified by this attribute on the main assembly. - -When you update the main assembly, you increment its assembly version number. However, you might not want to ship new copies of your satellite assemblies if the existing ones are compatible with your app. In this case, increment the main assembly's version number but leave the satellite contract version number the same. The resource manager will use your existing satellite assemblies. - -If you want to revise a satellite assembly but not the main assembly, increment the version number on your satellite. In this case, ship a publisher policy assembly along with your satellite assembly stating that your new satellite assembly has backward compatibility with your old satellite assembly. The resource manager will still use the old contract number written into your main assembly based on the attribute; however, the loader will bind to the satellite assembly version that is specified by the policy assembly. - -A vendor of a shared component uses a publisher policy assembly to make a compatibility statement about a particular version of a released assembly. A publisher policy assembly is a strongly named assembly that has a name in the format `policy...`, and is registered in the [Global Assembly Cache (GAC)](../../framework/app-domains/gac.md). The publisher policy is generated from an XML configuration file (see the [`` Element](../../framework/configure-apps/file-schema/runtime/bindingredirect-element.md)) by using the [Al.exe (Assembly Linker)](../../framework/tools/al-exe-assembly-linker.md) tool. The Assembly Linker is used with the `/link` option to link the XML configuration file to a manifest assembly, which is then stored in the global assembly cache. The publisher policy assemblies can be used when a vendor ships a maintenance release (service pack) that contains bug fixes. - -## Windows 8.x Store apps - -This attribute is ignored in Windows 8.x Store apps, because package resource index (PRI) files do not have versioning semantics. In addition, the Windows 8.x Store packaging model requires all resources to ship in the same package, with no possibility of redeploying satellite assemblies or PRI files. diff --git a/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-internalsvisibletoattribute.md b/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-internalsvisibletoattribute.md deleted file mode 100644 index ea6b3cd9aaa33..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-internalsvisibletoattribute.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: System.Runtime.CompilerServices.InternalsVisibleToAttribute class -description: Learn about the System.Runtime.CompilerServices.InternalsVisibleToAttribute class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Runtime.CompilerServices.InternalsVisibleToAttribute class - -[!INCLUDE [context](includes/context.md)] - -The attribute specifies that types that are ordinarily visible only within the current assembly are visible to a specified assembly. - -Ordinarily, types and members with [`internal` scope in C#](../../csharp/language-reference/keywords/internal.md) or [`Friend` scope in Visual Basic](../../visual-basic/language-reference/modifiers/friend.md) are visible only in the assembly in which they are defined. Types and members with [`protected internal`](../../csharp/language-reference/keywords/protected-internal.md) scope ([`Protected Friend`](../../visual-basic/language-reference/modifiers/protected-friend.md) scope in Visual Basic) are visible only in their own assembly or to types that derive from their containing class. Types and members with [`private protected`](../../csharp/language-reference/keywords/private-protected.md) scope ([`Private Protected`](../../visual-basic/language-reference/modifiers/private-protected.md) scope in Visual Basic) are visible in the containing class or in types that derive from their containing class within the current assembly - -The attribute makes these types and members also visible to the types in a specified assembly, which is known as a friend assembly. This applies only to `internal` (`Friend` in Visual Basic), `protected internal`(`Protected Friend` in Visual Basic), and `private protected` (`Private Protected` in Visual Basic) members, but not `private` ones. - -> [!NOTE] -> In the case of `private protected` (`Private Protected` in Visual Basic) members, the attribute extends accessibility only to types that derive from the *containing class* of the member. - -The attribute is applied at the assembly level. This means that it can be included at the beginning of a source code file, or it can be included in the AssemblyInfo file in a Visual Studio project. You can use the attribute to specify a single friend assembly that can access the internal types and members of the current assembly. You can define multiple friend assemblies in two ways. They can appear as individual assembly-level attributes, as the following example illustrates. - -:::code language="csharp" source="./snippets/System.Runtime.CompilerServices/InternalsVisibleToAttribute/Overview/csharp/multiple1.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Runtime.CompilerServices/InternalsVisibleToAttribute/Overview/vb/multiple1.vb" id="Snippet3"::: - -They can also appear with separate tags but a single `assembly` keyword, as the following example illustrates. - -:::code language="csharp" source="./snippets/System.Runtime.CompilerServices/InternalsVisibleToAttribute/Overview/csharp/multiple2.cs" id="Snippet4"::: -:::code language="vb" source="./snippets/System.Runtime.CompilerServices/InternalsVisibleToAttribute/Overview/vb/multiple2.vb" id="Snippet4"::: - -The friend assembly is identified by the constructor. Both the current assembly and the friend assembly must be unsigned, or both assemblies must be signed with a strong name. - -If both assemblies are unsigned, the `assemblyName` argument consists of the name of the friend assembly, specified without a directory path or file name extension. - -If both assemblies are signed with a strong name, the argument to the constructor must consist of the name of the assembly without its directory path or file name extension, along with the full public key (and not its public key token). To get the full public key of a strong-named assembly, see the [Get the full public key](#get-the-full-public-key) section later in this article. For more information about using with strong-named assemblies, see the constructor. - -Do not include values for the , , or field in the argument; the Visual Basic, C#, and C++ compilers treat this as a compiler error. If you use a compiler that does not treat it as an error (such as the [IL Assembler (ILAsm.exe)](../../framework/tools/ilasm-exe-il-assembler.md)) and the assemblies are strong-named, a exception is thrown the first time the specified friend assembly accesses the assembly that contains the attribute. - -For more information about how to use this attribute, see [Friend assemblies](../../standard/assembly/friend.md) and [C++ friend assemblies](/cpp/dotnet/friend-assemblies-cpp). - -## Get the full public key - -You can use the [Strong Name Tool (Sn.exe)](../../framework/tools/sn-exe-strong-name-tool.md) to retrieve the full public key from a strong-named key (.snk) file. To do this, you perform the following steps: - -1. Extract the public key from the strong-named key file to a separate file: - - `Sn -p ` - -2. Display the full public key to the console: - - `Sn -tp ` - -3. Copy and paste the full public key value into your source code. - -## Compile the friend assembly with C\# - -If you use the C# compiler to compile the friend assembly, 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. The **/out** compiler option is optional for the Visual Basic compiler, and the corresponding **-out** or **-o** compiler option should not be used when compiling friend assemblies with the F# compiler. - -## Compile the friend assembly with C++ - -In C++, in order to make the internal members enabled by the attribute accessible to a friend assembly, you must use the `as_friend` attribute in the C++ directive. For more information, see [Friend Assemblies (C++)](/cpp/dotnet/friend-assemblies-cpp). diff --git a/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-runtimehelpers-gethashcode.md b/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-runtimehelpers-gethashcode.md deleted file mode 100644 index b540172fade10..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-compilerservices-runtimehelpers-gethashcode.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode method -description: Learn about the System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode method. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - VB ---- -# System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode method - -[!INCLUDE [context](includes/context.md)] - -The method always calls the method non-virtually, even if the object's type has overridden the method. Therefore, using might differ from calling `GetHashCode` directly on the object with the method. - -> [!WARNING] -> Although the method returns identical hash codes for identical object references, you should not use this method to test for object identity, because this hash code does not uniquely identify an object reference. To test for object identity (that is, to test that two objects reference the same object in memory), call the method. Nor should you use to test whether two strings represent equal object references, because the string is interned. To test for string interning, call the method. - -The and methods differ as follows: - -- returns a hash code that is based on the object's definition of equality. For example, two strings with identical contents will return the same value for . -- returns a hash code that indicates object identity. That is, two string variables whose contents are identical and that represent a string that is interned (see the [String Interning](#string-interning) section) or that represent a single string in memory return identical hash codes. - -> [!IMPORTANT] -> Note that always returns identical hash codes for equal object references. However, the reverse is not true: equal hash codes do not indicate equal object references. A particular hash code value is not unique to a particular object reference; different object references can generate identical hash codes. - -This method is used by compilers. - -## String interning - -The common language runtime (CLR) maintains an internal pool of strings and stores literals in the pool. If two strings (for example, `str1` and `str2`) are formed from an identical string literal, the CLR will set `str1` and `str2` to point to the same location on the managed heap to conserve memory. Calling on these two string objects will produce the same hash code, contrary to the second bulleted item in the previous section. - -The CLR adds only literals to the pool. Results of string operations such as concatenation are not added to the pool, unless the compiler resolves the string concatenation as a single string literal. Therefore, if `str2` was created as the result of a concatenation operation, and `str2` is identical to `str1`, using on these two string objects will not produce the same hash code. - -If you want to add a concatenated string to the pool explicitly, use the method. - -You can also use the method to check whether a string has an interned reference. - -## Examples - -The following example demonstrates the difference between the and methods. The output from the example illustrates the following: - -- Both sets of hash codes for the first set of strings passed to the `ShowHashCodes` method are different, because the strings are completely different. - -- generates the same hash code for the second set of strings passed to the `ShowHashCodes` method, because the strings are equal. However, the method does not. The first string is defined by using a string literal and so is interned. Although the value of the second string is the same, it is not interned, because it is returned by a call to the method. - -- In the case of the third string, the hash codes produced by for both strings are identical, as are the hash codes produced by . This is because the compiler has treated the value assigned to both strings as a single string literal, and so the string variables refer to the same interned string. - -:::code language="csharp" source="./snippets/System.Runtime.CompilerServices/RuntimeHelpers/GetHashCode/csharp/gethashcodeex1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Runtime.CompilerServices/RuntimeHelpers/GetHashCode/vb/gethashcodeex1.vb" id="Snippet1"::: diff --git a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-comexception.md b/docs/fundamentals/runtime-libraries/system-runtime-interopservices-comexception.md deleted file mode 100644 index 6ac301d7a070b..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-comexception.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: System.Runtime.InteropServices.COMException class -description: Learn about the System.Runtime.InteropServices.COMException class. -ms.date: 12/31/2023 ---- -# System.Runtime.InteropServices.COMException class - -[!INCLUDE [context](includes/context.md)] - -The class is the exception that's thrown when an unrecognized HRESULT is returned from a COM method call. - -The common language runtime transforms well-known HRESULTs to .NET exceptions, enabling COM objects to return meaningful error information to managed clients. The HRESULT-to-exception mapping also works in the other direction by returning specific HRESULTs to unmanaged clients. For mapping details, see [How to map HRESULTs and exceptions](../../framework/interop/how-to-map-hresults-and-exceptions.md). - -When the runtime encounters an unfamiliar HRESULT (an HRESULT that lacks a specific, corresponding exception), it throws an instance of the class. This all-purpose exception exposes the same members as any exception, and inherits a public property that contains the HRESULT returned by the callee. If an error message is available to the runtime (obtained from the [IErrorInfo](/previous-versions/windows/desktop/ms723041(v=vs.85)) interface or the `Err` object in Visual Basic, or in some cases from the operating system), the message is returned to the caller. However, if the COM component developer fails to include an error message, the runtime returns the eight-digit HRESULT in place of a message string. Having an HRESULT allows the caller to determine the cause of the generic exception. - -## Handle a COMException exception - -The following are some considerations for troubleshooting a exception. - -Check the property -When the runtime encounters an unfamiliar HRESULT and throws a exception, the property includes either the error message or, if an error message is unavailable, the eight-digit HRESULT value. The error message or the HRESULT value can help you determine the cause of the exception. - -For a list of HRESULT values, see [Common HRESULT Values](/windows/win32/seccrypto/common-hresult-values). - -When passing late-bound arguments to methods of Microsoft Office objects, a exception may be thrown when the objects are COM objects. The late binder assumes that such method calls involve a `ByRef` parameter and that the property you pass has a `set` accessor. If the property does not, .NET generates a exception (with a `CORE_E_MISSINGMETHOD` HRESULT ). To work around this behavior, use early-bound objects or pass a variable instead of a property of the object. - -COM is used to communicate between Visual Studio and the [hosting process](/visualstudio/ide/hosting-process-vshost-exe?preserve-view=vs-2015). Because it is used before code runs, a call to [CoInitializeSecurity](/windows/win32/api/combaseapi/nf-combaseapi-coinitializesecurity) causes this exception to be thrown. In some cases, running Visual Studio as Administrator may resolve the issue. You can also [disable the hosting process](/visualstudio/ide/how-to-disable-the-hosting-process?preserve-view=vs-2015). - -## Throw a COMException exception - -Although you can use the class to return specific HRESULTs to unmanaged clients, throwing a specific .NET exception is better than using a generic exception. Consider that managed clients as well as unmanaged clients can use your .NET object, and throwing an HRESULT to a managed caller is less comprehensible than throwing an exception. diff --git a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-comwrappers.md b/docs/fundamentals/runtime-libraries/system-runtime-interopservices-comwrappers.md deleted file mode 100644 index bd796aaaab98c..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-comwrappers.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: System.Runtime.InteropServices.ComWrappers class -description: Learn about the System.Runtime.InteropServices.ComWrappers class. -ms.date: 12/31/2023 ---- -# System.Runtime.InteropServices.ComWrappers class - -[!INCLUDE [context](includes/context.md)] - -The API provides support for the `IUnknown` API independent of the built-in COM interoperability support. The `ComWrappers` API exposes the minimal runtime support that's needed for developers to replace the built-in version in an efficient manner. - -Traditionally in the runtime, a native proxy to managed object is called a COM Callable Wrapper (CCW), and a managed proxy to a native object is called a Runtime Callable Wrapper (RCW). However, when used here, those terms should not be confused with the built-in features of the same name (that is, [CCW](../../standard/native-interop/com-callable-wrapper.md) and [RCW](../../standard/native-interop/runtime-callable-wrapper.md)). Unlike the built-in features, a majority of the responsibility for accurate lifetime management, dispatching methods, and marshalling of arguments and return values is left to the `ComWrappers` implementer. - -"Minimal support" is defined by the following features: - -1. Efficient mapping between a managed object and a native proxy (for example, CCW). -2. Efficient mapping between a native `IUnknown` and its managed proxy (for example, RCW). -3. Integration with the garbage collector through the [IReferenceTrackerHost](/windows/win32/api/windows.ui.xaml.hosting.referencetracker/nn-windows-ui-xaml-hosting-referencetracker-ireferencetrackerhost) interface contract. - -Leveraging this is an advanced scenario. - -## Proxy state - -This section provides descriptions and illustrations of native and managed proxy state after their respective creation. - -In the following illustrations, a strong reference is depicted as a solid line (`===`) and a weak reference is depicted as a dashed line (`= = =`). The terms "strong reference" and "weak reference" should be interpreted as "extending lifetime" and "not extending lifetime", as opposed to implying a specific implementation. - -The following illustration shows the state of the managed object and native proxy after a call to . - -``` - -------------------- ---------------------- -| Managed object | | Native proxy | -| | | Ref count: 1 | -| ---------------- | | ------------------ | -| | Weak reference |=| = = = = = = = >| | Strong reference | | -| | to proxy | |<===============|=| to object | | -| ---------------- | | ------------------ | - -------------------- ---------------------- -``` - -The next illustration shows the state of the native object and managed proxy after a call to . The concept of "identity" follows the [rules for `IUnknown`](/windows/win32/com/rules-for-implementing-queryinterface#objects-must-have-identity). - -``` - ------------------ ------------------ -| Native object |< = = = = = =| | -| Ref count: +1 | | Mapping from | - ------------------ | native identity | - ------------------------ | to managed proxy | -| Managed proxy |< = = =| | -| Created by ComWrappers | ------------------ -| implementer. | -| Optional AddRef() on | -| native object. | - ------------------------ -``` - -Observe that only weak references exist from the runtime perspective. The `+1` reference count on the native object is assumed to be performed by the managed proxy creator (that is, the `ComWrappers` implementer) to ensure the associated lifetime between the native object and its managed proxy. There is an optional strong reference (that is, `AddRef()`) mentioned in the managed proxy, which is used to support scenario (3) mentioned earlier. See . With this optional strong reference, the reference count would be `+2`. diff --git a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-icustommarshaler.md b/docs/fundamentals/runtime-libraries/system-runtime-interopservices-icustommarshaler.md deleted file mode 100644 index 825f99d938bb5..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-icustommarshaler.md +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: System.Runtime.InteropServices.ICustomMarshaler interface -description: Learn about the System.Runtime.InteropServices.ICustomMarshaler interface. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Runtime.InteropServices.ICustomMarshaler interface - -[!INCLUDE [context](includes/context.md)] - -The interface provides custom wrappers for handling method calls. - -A marshaller provides a bridge between the functionality of old and new interfaces. Custom marshaling provides the following benefits: - -- It enables client applications that were designed to work with an old interface to also work with servers that implement a new interface. -- It enables client applications built to work with a new interface to work with servers that implement an old interface. - -If you have an interface that introduces different marshaling behavior or that is exposed to the Component Object Model (COM) in a different way, you can design a custom marshaller instead of using the interop marshaller. By using a custom marshaller, you can minimize the distinction between new .NET Framework components and existing COM components. - -For example, suppose that you are developing a managed interface called `INew`. When this interface is exposed to COM through a standard COM callable wrapper (CCW), it has the same methods as the managed interface and uses the marshaling rules built into the interop marshaller. Now suppose that a well-known COM interface called `IOld` already provides the same functionality as the `INew` interface. By designing a custom marshaller, you can provide an unmanaged implementation of `IOld` that simply delegates the calls to the managed implementation of the `INew` interface. Therefore, the custom marshaller acts as a bridge between the managed and unmanaged interfaces. - -> [!NOTE] -> Custom marshallers are not invoked when calling from managed code to unmanaged code on a dispatch-only interface. - -## Define the marshaling type - -Before you can build a custom marshaller, you must define the managed and unmanaged interfaces that will be marshaled. These interfaces commonly perform the same function but are exposed differently to managed and unmanaged objects. - -A managed compiler produces a managed interface from metadata, and the resulting interface looks like any other managed interface. The following example shows a typical interface. - -:::code language="csharp" source="./snippets/System.Runtime.InteropServices/ICustomMarshaler/Overview/csharp/source.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Runtime.InteropServices/ICustomMarshaler/Overview/vb/source.vb" id="Snippet1"::: - -You define the unmanaged type in Interface Definition Language (IDL) and compile it with the Microsoft Interface Definition Language (MIDL) compiler. You define the interface within a library statement and assign it an interface ID with the universal unique identifier (UUID) attribute, as the following example demonstrates. - -``` - [uuid(9B2BAADA-0705-11D3-A0CD-00C04FA35826)] -library OldLib { - [uuid(9B2BAADD-0705-11D3-A0CD-00C04FA35826)] - interface IOld : IUnknown - HRESULT OldMethod(); -} -``` - -The MIDL compiler produces several output files. If the interface is defined in Old.idl, the output file Old_i.c defines a `const` variable with the interface identifier (IID) of the interface, as the following example demonstrates. - -``` -const IID IID_IOld = {0x9B2BAADD,0x0705,0x11D3,{0xA0,0xCD,0x00,0xC0,0x4F,0xA3,0x58,0x26}}; -``` - -The Old.h file is also produced by MIDL. It contains a C++ definition of the interface that can be included in your C++ source code. - -## Implement the ICustomMarshaler interface - -Your custom marshaller must implement the interface to provide the appropriate wrappers to the runtime. - -The following C# code displays the base interface that must be implemented by all custom marshallers. - -:::code language="csharp" source="./snippets/System.Runtime.InteropServices/ICustomMarshaler/Overview/csharp/source.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Runtime.InteropServices/ICustomMarshaler/Overview/vb/source.vb" id="Snippet2"::: - -The interface includes methods that provide conversion support, cleanup support, and information about the data to be marshaled. - -|Type of operation|ICustomMarshaler method|Description| -|-----------------------|-----------------------------|-----------------| -|Conversion (from native to managed code)||Marshals a pointer to native data into a managed object. This method returns a custom runtime callable wrapper (RCW) that can marshal the unmanaged interface that is passed as an argument. The marshaller should return an instance of the custom RCW for that type.| -|Conversion (from managed to native code)||Marshals a managed object into a pointer to native data. This method returns a custom COM callable wrapper (CCW) that can marshal the managed interface that is passed as an argument. The marshaller should return an instance of the custom CCW for that type.| -|Cleanup (of native code)||Enables the marshaller to clean up the native data (the CCW) that is returned by the method.| -|Cleanup (of managed code)||Enables the marshaller to clean up the managed data (the RCW) that is returned by the method.| -|Information (about native code)||Returns the size of the unmanaged data to be marshaled.| - -### Conversion - - - -Marshals a pointer to native data into a managed object. This method returns a custom runtime callable wrapper (RCW) that can marshal the unmanaged interface that is passed as an argument. The marshaller should return an instance of the custom RCW for that type. - - - -Marshals a managed object into a pointer to native data. This method returns a custom COM callable wrapper (CCW) that can marshal the managed interface that is passed as an argument. The marshaller should return an instance of the custom CCW for that type. - -### Cleanup - - - -Enables the marshaller to clean up the native data (the CCW) that is returned by the method. - - - -Enables the marshaller to clean up the managed data (the RCW) that is returned by the method. - -### Size information - - - -Returns the size of the unmanaged data to be marshaled. - -> [!NOTE] -> If a custom marshaller calls any methods that set the last P/Invoke error when marshaling from native to managed or when cleaning up, the value returned by and will represent the call in the marshaling or cleanup calls. This can cause errors to be missed when using custom marshallers with P/Invokes with set to `true`. To preserve the last P/Invoke error, use the and methods in the implementation. - -## Implement the GetInstance method - -In addition to implementing the interface, custom marshallers must implement a `static` method called `GetInstance` that accepts a as a parameter and has a return type of . This `static` method is called by the common language runtime's COM interop layer to instantiate an instance of the custom marshaller. The string that is passed to `GetInstance` is a cookie that the method can use to customize the returned custom marshaller. The following example shows a minimal, but complete, implementation. - -:::code language="csharp" source="./snippets/System.Runtime.InteropServices/ICustomMarshaler/Overview/csharp/source.cs" id="Snippet6"::: - -## Apply MarshalAsAttribute - -To use a custom marshaller, you must apply the attribute to the parameter or field that is being marshaled. - -You must also pass the enumeration value to the constructor. In addition, you must specify the field with one of the following named parameters: - -- (required): The assembly-qualified name of the custom marshaller. The name should include the namespace and class of the custom marshaller. If the custom marshaller is not defined in the assembly it is used in, you must specify the name of the assembly in which it is defined. - - > [!NOTE] - > You can use the field instead of the field. takes a type that is easier to specify. - -- (optional): A cookie that is passed to the custom marshaller. You can use the cookie to provide additional information to the marshaller. For example, if the same marshaller is used to provide a number of wrappers, the cookie identifies a specific wrapper. The cookie is passed to the `GetInstance` method of the marshaller. - -The attribute identifies the custom marshaller so it can activate the appropriate wrapper. The common language runtime's interop service then examines the attribute and creates the custom marshaller the first time the argument (parameter or field) needs to be marshaled. - -The runtime then calls the and methods on the custom marshaller to activate the correct wrapper to handle the call. - -## Use a custom marshaller - -When the custom marshaller is complete, you can use it as a custom wrapper for a particular type. The following example shows the definition of the `IUserData` managed interface: - -:::code language="csharp" source="./snippets/System.Runtime.InteropServices/ICustomMarshaler/Overview/csharp/source.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Runtime.InteropServices/ICustomMarshaler/Overview/vb/source.vb" id="Snippet3"::: - -In the following example, the `IUserData` interface uses the `NewOldMarshaler` custom marshaller to enable unmanaged client applications to pass an `IOld` interface to the `DoSomeStuff` method. The managed description of the `DoSomeStuff` method takes an `INew` interface, as shown in the previous example, whereas the unmanaged version of `DoSomeStuff` takes an `IOld` interface pointer, as shown in the following example. - -``` -[uuid(9B2BAADA-0705-11D3-A0CD-00C04FA35826)] -library UserLib { - [uuid(9B2BABCD-0705-11D3-A0CD-00C04FA35826)] - interface IUserData : IUnknown - HRESULT DoSomeStuff(IUnknown* pIOld); -} -``` - -The type library that is generated by exporting the managed definition of `IUserData` yields the unmanaged definition shown in this example instead of the standard definition. The attribute applied to the `INew` argument in the managed definition of the `DoSomeStuff` method indicates that the argument uses a custom marshaller, as the following example shows. - -:::code language="csharp" source="./snippets/System.Runtime.InteropServices/ICustomMarshaler/Overview/csharp/source.cs" id="Snippet4"::: -:::code language="vb" source="./snippets/System.Runtime.InteropServices/ICustomMarshaler/Overview/vb/source.vb" id="Snippet4"::: - -:::code language="csharp" source="./snippets/System.Runtime.InteropServices/ICustomMarshaler/Overview/csharp/source.cs" id="Snippet5"::: -:::code language="vb" source="./snippets/System.Runtime.InteropServices/ICustomMarshaler/Overview/vb/source.vb" id="Snippet5"::: - -In the previous examples, the first parameter provided to the attribute is the enumeration value `UnmanagedType.CustomMarshaler`. - -The second parameter is the field, which provides the assembly-qualified name of the custom marshaller. This name consists of the namespace and class of the custom marshaller (`MarshalType="MyCompany.NewOldMarshaler"`). diff --git a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-marshal-getactiveobject.md b/docs/fundamentals/runtime-libraries/system-runtime-interopservices-marshal-getactiveobject.md deleted file mode 100644 index 376e5d0e5012c..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-marshal-getactiveobject.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: System.Runtime.InteropServices.Marshal.GetActiveObject method -description: Learn about the System.Runtime.InteropServices.Marshal.GetActiveObject method. -ms.date: 01/24/2024 ---- -# System.Runtime.InteropServices.Marshal.GetActiveObject method - -[!INCLUDE [context](includes/context.md)] - - exposes the COM [GetActiveObject](/windows/win32/api/oleauto/nf-oleauto-getactiveobject) function from OLEAUT32.DLL; however, the latter expects a class identifier (CLSID) instead of the programmatic identifier (`ProgID`) expected by this method. To obtain a running instance of a COM object without a registered `ProgID`, use platform invoke to define the COM [GetActiveObject](/windows/win32/api/oleauto/nf-oleauto-getactiveobject) function. For a description of platform invoke, see [Consuming Unmanaged DLL Functions](../../framework/interop/consuming-unmanaged-dll-functions.md). - -## ProgID and CLSID - -Keys in the HKEY_CLASSES_ROOT subtree of the registry contain a variety of subkey types. Most of the subkeys are ProgIDs, which map a user-friendly string to a CLSID. Applications often use these human-readable strings instead of the numeric CLSIDs. Often, a component has a version-independent ProgID that is mapped to the latest version of the component that is installed on the system. - -Applications and components primarily use ProgIDs to retrieve their corresponding CLSIDs. diff --git a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-safehandle.md b/docs/fundamentals/runtime-libraries/system-runtime-interopservices-safehandle.md deleted file mode 100644 index 98156b79914ec..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-interopservices-safehandle.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -title: System.Runtime.InteropServices.SafeHandle class -description: Learn about the System.Runtime.InteropServices.SafeHandle class. -ms.date: 12/31/2023 ---- -# System.Runtime.InteropServices.SafeHandle class - -[!INCLUDE [context](includes/context.md)] - -The class provides critical finalization of handle resources, preventing handles from being reclaimed prematurely by garbage collection and from being recycled by the operating system to reference unintended unmanaged objects. - -## Why SafeHandle? - -Although overrides to the method allow cleanup of unmanaged resources when an object is being garbage collected, in some circumstances, finalizable objects can be reclaimed by garbage collection while executing a method within a platform invoke call. If a finalizer frees the handle passed to that platform invoke call, it could lead to handle corruption. The handle could also be reclaimed while your method is blocked during a platform invoke call, such as while reading a file. - -More critically, because Windows aggressively recycles handles, a handle could be recycled and point to another resource that might contain sensitive data. This is known as a recycle attack and can potentially corrupt data and be a security threat. - -## What SafeHandle does - -The class simplifies several of these object lifetime issues, and is integrated with platform invoke so that operating system resources are not leaked. The class resolves object lifetime issues by assigning and releasing handles without interruption. It contains a critical finalizer that ensures that the handle is closed and is guaranteed to run during unexpected unloads, even in cases when the platform invoke call is assumed to be in a corrupted state. - -Because inherits from , all the noncritical finalizers are called before any of the critical finalizers. The finalizers are called on objects that are no longer live during the same garbage collection pass. For example, a object can run a normal finalizer to flush out existing buffered data without the risk of the handle being leaked or recycled. This very weak ordering between critical and noncritical finalizers is not intended for general use. It exists primarily to assist in the migration of existing libraries by allowing those libraries to use without altering their semantics. Additionally, the critical finalizer and anything it calls, such as the method, must be in a constrained execution region. This imposes constraints on what code can be written within the finalizer's call graph. - -Platform invoke operations automatically increment the reference count of handles encapsulated by a and decrement them upon completion. This ensures that the handle will not be recycled or closed unexpectedly. - -You can specify ownership of the underlying handle when constructing objects by supplying a value to the `ownsHandle` argument in the class constructor. This controls whether the object will release the handle after the object has been disposed. This is useful for handles with peculiar lifetime requirements or for consuming a handle whose lifetime is controlled by someone else. - -## Classes derived from SafeHandle - - is an abstract wrapper class for operating system handles. Deriving from this class is difficult. Instead, use the derived classes in the namespace that provide safe handles for the following: - -- Files (the class). -- Memory mapped files (the class). -- Pipes (the class). -- Memory views (the class). -- Cryptography constructs (the , , , and classes). -- Processes (the class). -- Registry keys (the class). -- Wait handles (the class). diff --git a/docs/fundamentals/runtime-libraries/system-runtime-loader-assemblyloadcontext.md b/docs/fundamentals/runtime-libraries/system-runtime-loader-assemblyloadcontext.md deleted file mode 100644 index 9aa2415d62a3e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-loader-assemblyloadcontext.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: System.Runtime.Loader.AssemblyLoadContext class -description: Learn about the System.Runtime.Loader.AssemblyLoadContext class. -ms.date: 12/31/2023 ---- -# System.Runtime.Loader.AssemblyLoadContext class - -[!INCLUDE [context](includes/context.md)] - -The represents a load context. Conceptually, a load context creates a scope for loading, resolving, and potentially unloading a set of assemblies. - -The exists primarily to provide assembly loading isolation. It allows multiple versions of the same assembly to be loaded within a single process. It replaces the isolation mechanisms provided by multiple instances in .NET Framework. - -> [!NOTE] -> -> * does not provide any security features. All code has full permissions of the process. -> * In .NET Core 2.0 - 2.2 only, is an abstract class. To create a concrete class in these versions, implement the method. - -## Usage in the runtime - -The runtime implements two assembly load contexts: - -* represents the runtime's default context, which is used for the application main assembly and its static dependencies. -* The method isolates the assemblies it loads by instantiating the most basic . It has a simplistic isolation scheme that loads each assembly in its own with no dependency resolution. - -### Application usage - -An application can create its own to create a custom solution for advanced scenarios. The customization focuses on defining dependency resolution mechanisms. - -The provides two extension points to implement managed assembly resolution: - -1. The method provides the first chance for the to resolve, load, and return the assembly. If the method returns `null`, the loader tries to load the assembly into the . -2. If the is unable to resolve the assembly, the original gets a second chance to resolve the assembly. The runtime raises the event. - -Additionally, the virtual method allows customization of the default unmanaged assembly resolution. The default implementation returns `null`, which causes the runtime search to use its default search policy. The default search policy is sufficient for most scenarios. - -## Technical challenges - -* It's not possible to load multiple versions of the runtime in a single process. - - > [!CAUTION] - > Loading multiple copies or different versions of framework assemblies can lead to unexpected and hard-to-diagnose behavior. - - > [!TIP] - > Use process boundaries with remoting or interprocess communication to solve this isolation problem. - -* The timing of assembly loading can make testing and debugging difficult. Assemblies are typically loaded without their dependencies immediately being resolved. The dependencies are loaded as they are needed: - - * When code branches into a dependent assembly. - * When code loads resources. - * When code explicitly loads assemblies. - -* The implementation of can add new dependencies that may need to be isolated to allow different versions to exist. The most natural implementation would place these dependencies in the default context. Careful design can isolate the new dependencies. - -* The same assembly is loaded multiple times into different contexts. - - * This can lead to confusing error messages, for example "Unable to cast object of type 'Sample.Plugin' to type 'Sample.Plugin'". - * Marshaling across isolation boundaries is non-trivial. A typical solution is to use an interface defined in an assembly that's only loaded into the default load context. diff --git a/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractattribute.md b/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractattribute.md deleted file mode 100644 index 014fc352d3885..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractattribute.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: System.Runtime.Serialization.DataContractAttribute class -description: Learn about the System.Runtime.Serialization.DataContractAttribute class. -ms.date: 12/31/2023 ---- -# System.Runtime.Serialization.DataContractAttribute class - -[!INCLUDE [context](includes/context.md)] - -Apply the attribute to types (classes, structures, or enumerations) that are used in serialization and deserialization operations by the . If you send or receive messages by using the Windows Communication Foundation (WCF) infrastructure, you should also apply the to any classes that hold and manipulate data sent in messages. For more information about data contracts, see [Using Data Contracts](../../framework/wcf/feature-details/using-data-contracts.md). - -You must also apply the to any field, property, or event that holds values you want to serialize. By applying the , you explicitly enable the to serialize and deserialize the data. - -> [!CAUTION] -> You can apply the to private fields. Be aware that the data returned by the field (even if it is private) is serialized and deserialized, and thus can be viewed or intercepted by a malicious user or process. - -For more information about data contracts, see the topics listed in [Using Data Contracts](../../framework/wcf/feature-details/using-data-contracts.md). - -## Data contracts - -A *data contract* is an abstract description of a set of fields with a name and data type for each field. The data contract exists outside of any single implementation to allow services on different platforms to interoperate. As long as the data passed between the services conforms to the same contract, all the services can process the data. This processing is also known as a *loosely coupled system*. A data contract is also similar to an interface in that the contract specifies how data must be delivered so that it can be processed by an application. For example, the data contract may call for a data type named "Person" that has two text fields, named "FirstName" and "LastName". To create a data contract, apply the to the class and apply the to any fields or properties that must be serialized. When serialized, the data conforms to the data contract that is implicitly built into the type. - -> [!NOTE] -> A data contract differs significantly from an actual interface in its inheritance behavior. Interfaces are inherited by any derived types. When you apply the to a base class, the derived types do not inherit the attribute or the behavior. However, if a derived type has a data contract, the data members of the base class are serialized. However, you must apply the to new members in a derived class to make them serializable. - -## XML schema documents and the SvcUtil tool - -If you are exchanging data with other services, you must describe the data contract. For the current version of the , an XML schema can be used to define data contracts. (Other forms of metadata/description could be used for the same purpose.) To create an XML schema from your application, use the [ServiceModel Metadata Utility Tool (Svcutil.exe)](../../framework/wcf/servicemodel-metadata-utility-tool-svcutil-exe.md) with the **/dconly** command line option. When the input to the tool is an assembly, by default, the tool generates a set of XML schemas that define all the data contract types found in that assembly. Conversely, you can also use the Svcutil.exe tool to create Visual Basic or C# class definitions that conform to the requirements of XML schemas that use constructs that can be expressed by data contracts. In this case, the **/dconly** command line option is not required. - -If the input to the Svcutil.exe tool is an XML schema, by default, the tool creates a set of classes. If you examine those classes, you find that the has been applied. You can use those classes to create a new application to process data that must be exchanged with other services. - -You can also run the tool against an endpoint that returns a Web Services Description Language (WSDL) document to automatically generate the code and configuration to create an Windows Communication Foundation (WCF) client. The generated code includes types that are marked with the . - -## Reuse existing types - -A data contract has two basic requirements: a stable name and a list of members. The stable name consists of the namespace uniform resource identifier (URI) and the local name of the contract. By default, when you apply the to a class, it uses the class name as the local name and the class's namespace (prefixed with `"http://schemas.datacontract.org/2004/07/"`) as the namespace URI. You can override the defaults by setting the and properties. You can also change the namespace by applying the to the namespace. Use this capability when you have an existing type that processes data exactly as you require but has a different namespace and class name from the data contract. By overriding the default values, you can reuse your existing type and have the serialized data conform to the data contract. - -> [!NOTE] -> In any code, you can use the word `DataContract` instead of the longer . - -## Versioning - -A data contract can also accommodate later versions of itself. That is, when a later version of the contract includes extra data, that data is stored and returned to a sender untouched. To do this, implement the interface. - -For more information about versioning, see [Data Contract Versioning](../../framework/wcf/feature-details/data-contract-versioning.md). diff --git a/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractserializer.md b/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractserializer.md deleted file mode 100644 index b0d654dd5cec3..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-serialization-datacontractserializer.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: System.Runtime.Serialization.DataContractSerializer class -description: Learn about the System.Runtime.Serialization.DataContractSerializer class. -ms.date: 12/31/2023 ---- -# System.Runtime.Serialization.DataContractSerializer class - -[!INCLUDE [context](includes/context.md)] - -Use the class to serialize and deserialize instances of a type into an XML stream or document. For example, you can create a type named `Person` with properties that contain essential data, such as a name and address. You can then create and manipulate an instance of the `Person` class and write all of its property values in an XML document for later retrieval, or in an XML stream for immediate transport. Most important, the is used to serialize and deserialize data sent in Windows Communication Foundation (WCF) messages. Apply the attribute to classes, and the attribute to class members to specify properties and fields that are serialized. - -For a list of types that can be serialized, see [Types Supported by the Data Contract Serializer](../../framework/wcf/feature-details/types-supported-by-the-data-contract-serializer.md). - -To use the , first create an instance of a class and an object appropriate to writing or reading the format; for example, an instance of the . Then call the method to persist the data. To retrieve data, create an object appropriate to reading the data format (such as an for an XML document) and call the method. - -For more information about using the , see [Serialization and Deserialization](../../framework/wcf/feature-details/serialization-and-deserialization.md). - -You can set the type of a data contract serializer using the [<dataContractSerializer>](../../framework/configure-apps/file-schema/wcf/datacontractserializer-element.md) element in a client application configuration file. - -## Prepare classes for serialization or deserialization - -The is used in combination with the and classes. To prepare a class for serialization, apply the to the class. For each member of the class that returns data that you want to serialize, apply the . You can serialize fields and properties, regardless of accessibility: private, protected, internal, protected internal, or public. - -For example, your schema specifies a `Customer` with an `ID` property, but you already have an existing application that uses a type named `Person` with a `Name` property. To create a type that conforms to the contract, first apply the to the class. Then apply the to every field or property that you want to serialize. - -> [!NOTE] -> You can apply the to both private and public members. - -The final format of the XML need not be text. Instead, the writes the data as an XML infoset, which allows you to write the data to any format recognized by the and . It is recommended that you use the and classes to read and write, because both are optimized to work with the . - -If you are creating a class that has fields or properties that must be populated before the serialization or deserialization occurs, use callback attributes, as described in [Version-Tolerant Serialization Callbacks](../../framework/wcf/feature-details/version-tolerant-serialization-callbacks.md). - -## Add to the collection of known types - -When serializing or deserializing an object, it is required that the type is "known" to the . Begin by creating an instance of a class that implements (such as ) and adding the known types to the collection. Then create an instance of the using one of the overloads that takes the (for example, ). - -> [!NOTE] -> Unlike other primitive types, the structure is not a known type by default, so it must be manually added to the list of known types (see [Data Contract Known Types](../../framework/wcf/feature-details/data-contract-known-types.md)). - -## Forward compatibility - -The understands data contracts that have been designed to be compatible with future versions of the contract. Such types implement the interface. The interface features the property that returns an object. For more information, see [Forward-Compatible Data Contracts](../../framework/wcf/feature-details/forward-compatible-data-contracts.md). - -## Run under partial trust - -When instantiating the target object during deserialization, the does not call the constructor of the target object. If you author a *[DataContract]* type that is accessible from partial trust (that is, it is public and in an assembly that has the `AllowPartiallyTrustedCallers` attribute applied) and that performs some security-related actions, you must be aware that the constructor is not called. In particular, the following techniques do not work: - -- If you try to restrict partial trust access by making the constructor internal or private, or by adding a `LinkDemand` to the constructor -- neither of these have any effect during deserialization under partial trust. -- If you code the class that assumes the constructor has run, the class may get into an invalid internal state that is exploitable. diff --git a/docs/fundamentals/runtime-libraries/system-runtime-serialization-iextensibledataobject.md b/docs/fundamentals/runtime-libraries/system-runtime-serialization-iextensibledataobject.md deleted file mode 100644 index c398697021a05..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-serialization-iextensibledataobject.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -title: System.Runtime.Serialization.IExtensibleDataObject interface -description: Learn about the System.Runtime.Serialization.IExtensibleDataObject interface. -ms.date: 12/31/2023 ---- -# System.Runtime.Serialization.IExtensibleDataObject interface - -[!INCLUDE [context](includes/context.md)] - -The interface provides a single property that sets or returns a structure used to store data that is external to a data contract. The extra data is stored in an instance of the class and accessed through the property. In a roundtrip operation where data is received, processed, and sent back, the extra data is sent back to the original sender intact. This is useful to store data received from future versions of the contract. If you do not implement the interface, any extra data is ignored and discarded during a roundtrip operation. - -## To use this versioning feature - -1. Implement the interface in a class. - -2. Add the property to your type. - -3. Add a private member of type to the class. - -4. Implement get and set methods for the property using the new private member. - -5. Apply the attribute to the class. Set the and properties to appropriate values if necessary. - -For more information about versioning of types, see [Data Contract Versioning](../../framework/wcf/feature-details/data-contract-versioning.md). For information about creating forward-compatible data contracts, see [Forward-Compatible Data Contracts](../../framework/wcf/feature-details/forward-compatible-data-contracts.md). For more information about data contracts, see [Using Data Contracts](../../framework/wcf/feature-details/using-data-contracts.md). diff --git a/docs/fundamentals/runtime-libraries/system-runtime-serialization-xsddatacontractexporter.md b/docs/fundamentals/runtime-libraries/system-runtime-serialization-xsddatacontractexporter.md deleted file mode 100644 index 6af813e2f918b..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-serialization-xsddatacontractexporter.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: System.Runtime.Serialization.XsdDataContractExporter class -description: Learn about the System.Runtime.Serialization.XsdDataContractExporter class. -ms.date: 12/31/2023 ---- -# System.Runtime.Serialization.XsdDataContractExporter class - -[!INCLUDE [context](includes/context.md)] - -Use the class when you have created a Web service that incorporates data represented by common language runtime (CLR) types and when you need to export XML schemas for each type to be consumed by other Web services. That is, transforms a set of CLR types into XML schemas. (For more information about the types that can be used, see [Types Supported by the Data Contract Serializer](../../framework/wcf/feature-details/types-supported-by-the-data-contract-serializer.md).) The schemas can then be exposed through a Web Services Description Language (WSDL) document for use by others who need to interoperate with your service. - -Conversely, if you are creating a Web service that must interoperate with an existing Web service, use the to transform XML schemas and create the CLR types that represent the data in a selected programming language. - -The generates an object that contains the collection of schemas. Access the set of schemas through the property. - -> [!NOTE] -> To quickly generate XML schema definition (XSD) files that other Web services can consume, use the . - -## Export schemas into an XmlSchemaSet - -To create an instance of the class that contains XML schema files, you should be aware of the following. - -The set of types you are exporting are recorded as an internal set of data contracts. Thus, you can call the method multiple times to add new types to the schema set without degrading performance because only the new types will be added to the set. During the operation, the existing schemas are compared to the new schemas being added. If there are conflicts, an exception will be thrown. A conflict is usually detected if two types with the same data contract name but different contracts (different members) are exported by the same instance. - -## Use the exporter - -A recommended way of using this class is as follows: - -1. Use one of the overloads to determine whether the specified type or set of types can be exported. Use one of the overloads that is appropriate to your requirements. - -2. Call the corresponding method. - -3. Retrieve the schemas from the property. diff --git a/docs/fundamentals/runtime-libraries/system-runtime-versioning-componentguaranteesattribute.md b/docs/fundamentals/runtime-libraries/system-runtime-versioning-componentguaranteesattribute.md deleted file mode 100644 index 8602bb9d308d8..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-runtime-versioning-componentguaranteesattribute.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: System.Runtime.Versioning.ComponentGuaranteesAttribute class -description: Learn about the System.Runtime.Versioning.ComponentGuaranteesAttribute class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Runtime.Versioning.ComponentGuaranteesAttribute class - -[!INCLUDE [context](includes/context.md)] - -The is used by developers of components and class libraries to indicate the level of compatibility that consumers of their libraries can expect across multiple versions. It indicates the level of guarantee that a future version of the library or component will not break an existing client. Clients can then use the as an aid in designing their own interfaces to ensure stability across versions. - -> [!NOTE] -> The common language runtime (CLR) does not use this attribute in any way. Its value lies in formally documenting the intent of the component author. Compile-time tools can also use these declarations to detect compile-time errors that would otherwise break the declared guarantee. - -## Levels of compatibility - -The supports the following levels of compatibility, which are represented by members of the enumeration: - -- No version-to-version compatibility (). The client can expect that future versions will break the existing client. For more information, see the [No compatibility](#no-compatibility) section later in this article. - -- Side-by-side version-to-version compatibility (). The component has been tested to work when more than one version of the assembly is loaded in the same application domain. In general, future versions can break compatibility. However, when breaking changes are made, the old version is not modified but exists alongside the new version. Side-by-side execution is the expected way to make existing clients work when breaking changes are made. For more information, see the [Side-by-side compatibility](#side-by-side-compatibility) section later in this article. - -- Stable version-to-version compatibility (). Future versions should not break the client, and side-by-side execution should not be needed. However, if the client is inadvertently broken, it may be possible to use side-by-side execution to fix the problem. For more information, see the [Stable compatibility](#stable-compatibility) section. - -- Exchange version-to-version compatibility (). Extraordinary care is taken to ensure that future versions will not break the client. The client should use only these types in the signature of interfaces that are used for communication with other assemblies that are deployed independently of one another. Only one version of these types is expected to be in a given application domain, which means that if a client breaks, side-by-side execution cannot fix the compatibility problem. For more information, see the [Exchange type compatibility](#exchange-type-compatibility) section. - -The following sections discuss each level of guarantee in greater detail. - -### No compatibility - -Marking a component as indicates that the provider makes no guarantees about compatibility. Clients should avoid taking any dependencies on the exposed interfaces. This level of compatibility is useful for types that are experimental or that are publicly exposed but are intended only for components that are always updated at the same time. explicitly indicates that this component should not be used by external components. - -### Side-by-side compatibility - -Marking a component as indicates that the component has been tested to work when more than one version of the assembly is loaded into the same application domain. Breaking changes are allowed as long as they are made to the assembly that has the greater version number. Components that are bound to an old version of the assembly are expected to continue to bind to the old version, and other components can bind to the new version. It is also possible to update a component that is declared to be by destructively modifying the old version. - -### Stable compatibility - -Marking a type as indicates that the type should remain stable across versions. However, it may also be possible for side-by-side versions of a stable type to exist in the same application domain. - -Stable types maintain a high binary compatibility bar. Because of this, providers should avoid making breaking changes to stable types. The following kinds of changes are acceptable: - -- Adding private instance fields to, or removing fields from, a type, as long as this does not break the serialization format. -- Changing a non-serializable type to a serializable type. (However, a serializable type cannot be changed to a non-serializable type.) -- Throwing new, more derived exceptions from a method. -- Improving the performance of a method. -- Changing the range of return values, as long as the change does not adversely affect the majority of clients. -- Fixing serious bugs, if the business justification is high and the number of adversely affected clients is low. - -Because new versions of stable components are not expected to break existing clients, generally only one version of a stable component is needed in an application domain. However, this is not a requirement, because stable types are not used as well-known exchange types that all components agree upon. Therefore, if a new version of a stable component does inadvertently break some component, and if other components need the new version, it may be possible to fix the problem by loading both the old and new component. - - provides a stronger version compatibility guarantee than . It is a common default for multi-version components. - - can be combined with , which states that the component will not break compatibility but is tested to work when more than one version is loaded in a given application domain. - -After a type or method is marked as , it can be upgraded to . However, it cannot be downgraded to . - -### Exchange type compatibility - -Marking a type as provides a stronger version compatibility guarantee than , and should be applied to the most stable of all types. These types are intended to be used for interchange between independently built components across all component boundaries in both time (any version of the CLR or any version of a component or application) and space (cross-process, cross-CLR in one process, cross-application domain in one CLR). If a breaking change is made to an exchange type, it is impossible to fix the issue by loading multiple versions of the type. - -Exchange types should be changed only when a problem is very serious (such as a severe security issue) or the probability of breakage is very low (that is, if the behavior was already broken in a random way that code could not have conceivably taken a dependency on). You can make the following kinds of changes to an exchange type: - -- Add inheritance of new interface definitions. - -- Add new private methods that implement the methods of newly inherited interface definitions. - -- Add new static fields. - -- Add new static methods. - -- Add new non-virtual instance methods. - -The following are considered breaking changes and are not allowed for primitive types: - -- Changing serialization formats. Version-tolerant serialization is required. - -- Adding or removing private instance fields. This risks changing the serialization format of the type and breaking client code that uses reflection. - -- Changing the serializability of a type. A non-serializable type may not be made serializable, and vice versa. - -- Throwing different exceptions from a method. - -- Changing the range of a method's return values, unless the member definition raises this possibility and clearly indicates how clients should handle unknown values. - -- Fixing most bugs. Consumers of the type will rely on the existing behavior. - -After a component, type, or member is marked with the guarantee, it cannot be changed to either or . - -Typically, exchange types are the basic types (such as and in .NET) and interfaces (such as , , and ) that are commonly used in public interfaces. - -Exchange types may publicly expose only other types that are also marked with compatibility. In addition, exchange types cannot depend on the behavior of Windows APIs that are prone to change. - -## Component guarantees - -The following table indicates how a component's characteristics and usage affect its compatibility guarantee. - -|Component characteristics|Exchange|Stable|Side-by-Side|None| -|-------------------------------|--------------|------------|--------------------|----------| -|Can be used in interfaces between components that version independently.|Y|N|N|N| -|Can be used (privately) by an assembly that versions independently.|Y|Y|Y|N| -|Can have multiple versions in a single application domain.|N|Y|Y|Y| -|Can make breaking changes|N|N|Y|Y| -|Tested to make certain multiple versions of the assembly can be loaded together.|N|N|Y|N| -|Can make breaking changes in place.|N|N|N|Y| -|Can make very safe non-breaking servicing changes in place.|Y|Y|Y|Y| - -## Apply the attribute - -You can apply the to an assembly, a type, or a type member. Its application is hierarchical. That is, by default, the guarantee defined by the property of the attribute at the assembly level defines the guarantee of all types in the assembly and all members in those types. Similarly, if the guarantee is applied to the type, by default it also applies to each member of the type. - -This inherited guarantee can be overridden by applying the to individual types and type members. However, guarantees that override the default can only weaken the guarantee; they cannot strengthen it. For example, if an assembly is marked with the guarantee, its types and members have no compatibility guarantee, and any other guarantee that is applied to types or members in the assembly is ignored. - -## Test the guarantee - -The property returns a member of the enumeration, which is marked with the attribute. This means that you should test for the flag that you are interested in by masking away potentially unknown flags. For example, the following example tests whether a type is marked as . - -:::code language="csharp" source="./snippets/System.Runtime.Versioning/ComponentGuaranteesAttribute/Overview/csharp/apply1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Runtime.Versioning/ComponentGuaranteesAttribute/Overview/vb/apply1.vb" id="Snippet1"::: - -The following example tests whether a type is marked as or . - -:::code language="csharp" source="./snippets/System.Runtime.Versioning/ComponentGuaranteesAttribute/Overview/csharp/apply1.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Runtime.Versioning/ComponentGuaranteesAttribute/Overview/vb/apply1.vb" id="Snippet2"::: - -The following example tests whether a type is marked as (that is, neither nor ). - -:::code language="csharp" source="./snippets/System.Runtime.Versioning/ComponentGuaranteesAttribute/Overview/csharp/apply1.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Runtime.Versioning/ComponentGuaranteesAttribute/Overview/vb/apply1.vb" id="Snippet3"::: diff --git a/docs/fundamentals/runtime-libraries/system-security-cryptography-rsacryptoserviceprovider.md b/docs/fundamentals/runtime-libraries/system-security-cryptography-rsacryptoserviceprovider.md deleted file mode 100644 index 78aa267d49e79..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-security-cryptography-rsacryptoserviceprovider.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: System.Security.Cryptography.RSACryptoServiceProvider class -description: Learn about the System.Security.Cryptography.RSACryptoServiceProvider class. -ms.date: 12/31/2023 ---- -# System.Security.Cryptography.RSACryptoServiceProvider class - -[!INCLUDE [context](includes/context.md)] - -The class is the default implementation of . - -The supports key sizes from 384 bits to 16384 bits in increments of 8 bits if you have the Microsoft Enhanced Cryptographic Provider installed. It supports key sizes from 384 bits to 512 bits in increments of 8 bits if you have the Microsoft Base Cryptographic Provider installed. - -Valid key sizes are dependent on the cryptographic service provider (CSP) that is used by the instance. Windows CSPs enable keys sizes of 384 to 16384 bits for Windows versions prior to Windows 8.1, and key sizes of 512 to 16384 bits for Windows 8.1. For more information, see [CryptGenKey](/windows/win32/api/wincrypt/nf-wincrypt-cryptgenkey) function in the Windows documentation. - -## Interoperation with the Microsoft Cryptographic API (CAPI) - -Unlike the RSA implementation in unmanaged CAPI, the class reverses the order of an encrypted array of bytes after encryption and before decryption. By default, data encrypted by the class cannot be decrypted by the CAPI `CryptDecrypt` function and data encrypted by the CAPI `CryptEncrypt` method cannot be decrypted by the class. - -If you do not compensate for the reverse ordering when interoperating between APIs, the class throws a . - -To interoperate with CAPI, you must manually reverse the order of encrypted bytes before the encrypted data interoperates with another API. You can easily reverse the order of a managed byte array by calling the method. diff --git a/docs/fundamentals/runtime-libraries/system-security-cryptography-rsaparameters.md b/docs/fundamentals/runtime-libraries/system-security-cryptography-rsaparameters.md deleted file mode 100644 index 51537ab892289..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-security-cryptography-rsaparameters.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: System.Security.Cryptography.RSAParameters structure -description: Learn about the System.Security.Cryptography.RSAParameters structure. -ms.date: 12/31/2023 ---- -# System.Security.Cryptography.RSAParameters structure - -[!INCLUDE [context](includes/context.md)] - -The structure represents the standard parameters for the RSA algorithm. - -The class exposes an method that enables you to retrieve the raw RSA key in the form of an structure. - -To understand the contents of this structure, it helps to be familiar with how the algorithm works. The next section discusses the algorithm briefly. - -## RSA algorithm - -To generate a key pair, you start by creating two large prime numbers named p and q. These numbers are multiplied and the result is called n. Because p and q are both prime numbers, the only factors of n are 1, p, q, and n. - -If we consider only numbers that are less than n, the count of numbers that are relatively prime to n, that is, have no factors in common with n, equals (p - 1)(q - 1). - -Now you choose a number e, which is relatively prime to the value you calculated. The public key is now represented as {e, n}. - -To create the private key, you must calculate d, which is a number such that (d)(e) mod (p - 1)(q - 1) = 1. In accordance with the Euclidean algorithm, the private key is now {d, n}. - -Encryption of plaintext m to ciphertext c is defined as c = (m ^ e) mod n. Decryption would then be defined as m = (c ^ d) mod n. - -## Summary of fields - -Section A.1.2 of the [PKCS #1: RSA Cryptography Standard](https://datatracker.ietf.org/doc/html/rfc8017#appendix-A.1.2) defines a format for RSA private keys. - -The following table summarizes the fields of the structure. The third column provides the corresponding field in section A.1.2 of [PKCS #1: RSA Cryptography Standard](https://datatracker.ietf.org/doc/html/rfc8017#appendix-A.1.2). - -| field | Contains | Corresponding PKCS #1 field | -| ---------------------------------------------------------- | ----------------------- | --------------------------- | -| | d, the private exponent | privateExponent | -| | d mod (p - 1) | exponent1 | -| | d mod (q - 1) | exponent2 | -| | e, the public exponent | publicExponent | -| | (InverseQ)(q) = 1 mod p | coefficient | -| | n | modulus | -| | p | prime1 | -| | q | prime2 | - -The security of RSA derives from the fact that, given the public key { e, n }, it is computationally infeasible to calculate d, either directly or by factoring n into p and q. Therefore, any part of the key related to d, p, or q must be kept secret. If you call and ask for only the public key information, this is why you will receive only and . The other fields are available only if you have access to the private key, and you request it. - - is not encrypted in any way, so you must be careful when you use it with the private key information. All members of are serialized. If anyone can derive or intercept the private key parameters, the key and all the information encrypted or signed with it are compromised. diff --git a/docs/fundamentals/runtime-libraries/system-security-cryptography-xml-signedxml.md b/docs/fundamentals/runtime-libraries/system-security-cryptography-xml-signedxml.md deleted file mode 100644 index b4aacb566af71..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-security-cryptography-xml-signedxml.md +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: System.Security.Cryptography.Xml.SignedXml class -description: Learn about the System.Security.Cryptography.Xml.SignedXml class. -ms.date: 12/31/2023 ---- -# System.Security.Cryptography.Xml.SignedXml class - -[!INCLUDE [context](includes/context.md)] - -The class is the .NET implementation of the World Wide Web Consortium (W3C) [XML Signature Syntax and Processing Specification](https://www.w3.org/TR/xmldsig-core/), also known as XMLDSIG (XML Digital Signature). XMLDSIG is a standards-based, interoperable way to sign and verify all or part of an XML document or other data that is addressable from a Uniform Resource Identifier (URI). - -Use the class whenever you need to share signed XML data between applications or organizations in a standard way. Any data signed using this class can be verified by any conforming implementation of the W3C specification for XMLDSIG. - -The class allows you to create the following three kinds of XML digital signatures: - -| Signature Type | Description | -|----------------------|-----------------------------------------------------------------| -| Enveloped signature | The signature is contained within the XML element being signed. | -| Enveloping signature | The signed XML is contained within the `` element. | -| Internal detached signature | The signature and signed XML are in the same document, but neither element contains the other. | - -There is also a fourth kind of signature called an external detached signature which is when the data and signature are in separate XML documents. External detached signatures are not supported by the class. - -## Structure of an XML signature - -XMLDSIG creates a `` element, which contains a digital signature of an XML document or other data that is addressable from a URI. The `` element can optionally contain information about where to find a key that will verify the signature and which cryptographic algorithm was used for signing. The basic structure is as follows: - -```xml - - - - - - - - - - Base64EncodedValue== - - - AnotherBase64EncodedValue=== - -``` - -The main parts of this structure are: - -- The `` element - - Specifies the rules for rewriting the `Signature` element from XML/text into bytes for signature validation. The default value in .NET is , which identifies a trustworthy algorithm. This element is represented by the property. - -- The `` element - - Specifies the algorithm used for signature generation and validation, which was applied to the `` element to produce the value in ``. In the previous example, the value identifies an RSA PKCS1 SHA-1 signature. Due to collision problems with SHA-1, Microsoft recommends a security model based on SHA-256 or better. This element is represented by the property. - -- The `` element - - Specifies the cryptographic signature for the `` element. If this signature does not verify, then some portion of the `` block was tampered with, and the document is considered invalid. As long as the `` value is trustworthy, this value is highly resistant to tampering. This element is represented by the property. - -- The `URI` attribute of the `` element - - Specifies a data object using a URI reference. This attribute is represented by the property. - - - Not specifying the `URI` attribute, that is, setting the property to `null`, means that the receiving application is expected to know the identity of the object. In most cases, a `null` URI will result in an exception being thrown. Do not use a `null` URI, unless your application is interoperating with a protocol which requires it. - - - Setting the `URI` attribute to an empty string indicates that the root element of the document is being signed, a form of enveloped signature. - - - If the value of `URI` attribute starts with #, then the value must resolve to an element in the current document. This form can be used with any of the supported signature types (enveloped signature, enveloping signature or internal detached signature). - - - Anything else is considered an external resource detached signature and is not supported by the class. - -- The `` element - - Contains an ordered list of `` elements that describe how the signer obtained the data object that was digested. A transform algorithm is similar to the canonicalization method, but instead of rewriting the `` element, it rewrites the content identified by the `URI` attribute of the `` element. The `` element is represented by the class. - - - Each transform algorithm is defined as taking either XML (an XPath node-set) or bytes as input. If the format of the current data differs from the transform input requirements, conversion rules are applied. - - - Each transform algorithm is defined as producing either XML or bytes as the output. - - - If the output of the last transform algorithm is not defined in bytes (or no transforms were specified), then the [canonicalization method](https://www.w3.org/TR/2001/REC-xml-c14n-20010315) is used as an implicit transform (even if a different algorithm was specified in the `` element). - - - A value of for the transform algorithm encodes a rule which is interpreted as remove the `` element from the document. Otherwise, a verifier of an enveloped signature will digest the document, including the signature, but the signer would have digested the document before the signature was applied, leading to different answers. - -- The `` element - - Identifies the digest (cryptographic hash) method to apply on the transformed content identified by the `URI` attribute of the `` element. This is represented by the property. - -## Choosing a canonicalization method - -Unless interoperating with a specification which requires the use of a different value, we recommend that you use the default .NET canonicalization method, which is the XML-C14N 1.0 algorithm, whose value is . The XML-C14N 1.0 algorithm is required to be supported by all implementations of XMLDSIG, particularly as it is an implicit final transform to apply. - -There are versions of canonicalization algorithms which support preserving comments. Comment-preserving canonicalization methods are not recommended because they violate the "sign what is seen" principle. That is, the comments in a `` element will not alter the processing logic for how the signature is performed, merely what the signature value is. When combined with a weak signature algorithm, allowing the comments to be included gives an attacker unnecessary freedom to force a hash collision, making a tampered document appear legitimate. In .NET Framework, only built-in canonicalizers are supported by default. To support additional or custom canonicalizers, see the property. If the document uses a canonicalization method that is not in the collection represented by the property, then the method will return `false`. - -> [!NOTE] -> An extremely defensive application can remove any values it does not expect signers to use from the collection. - -## Are the reference values safe from tampering? - -Yes, the `` values are safe from tampering. .NET verifies the `` computation before processing any of the `` values and their associated transforms, and will abort early to avoid potentially malicious processing instructions. - -## Choose the elements to sign - -We recommend that you use the value of "" for the `URI` attribute (or set the property to an empty string), if possible. This means the whole document is considered for the digest computation, which means the whole document is protected from tampering. - -It is very common to see `URI` values in the form of anchors such as #foo, referring to an element whose ID attribute is "foo". Unfortunately, it is easy for this to be tampered with because this includes only the content of the target element, not the context. Abusing this distinction is known as XML Signature Wrapping (XSW). - -If your application considers comments to be semantic (which is not common when dealing with XML), then you should use "#xpointer(/)" instead of "", and "#xpointer(id('foo'))" instead of "#foo". The #xpointer versions are interpreted as including comments, while the shortname forms are excluding comments. - -If you need to accept documents which are only partially protected and you want to ensure that you are reading the same content that the signature protected, use the method. - -## Security considerations about the KeyInfo element - -The data in the optional `` element (that is, the property), which contains a key to validate the signature, should not be trusted. - -In particular, when the value represents a bare RSA, DSA or ECDSA public key, the document could have been tampered with, despite the method reporting that the signature is valid. This can happen because the entity doing the tampering just has to generate a new key and re-sign the tampered document with that new key. So, unless your application verifies that the public key is an expected value, the document should be treated as if it were tampered with. This requires that your application examine the public key embedded within the document and verify it against a list of known values for the document context. For example, if the document could be understood to be issued by a known user, you'd check the key against a list of known keys used by that user. - -You can also verify the key after processing the document by using the method, instead of using the method. But, for the optimal security, you should verify the key beforehand. - -Alternately, consider trying the user's registered public keys, rather than reading what's in the `` element. - -## Security considerations about the X509Data element - -The optional `` element is a child of the `` element and contains one or more X509 certificates or identifiers for X509 certificates. The data in the `` element should also not be inherently trusted. - -When verifying a document with the embedded `` element, .NET verifies only that the data resolves to an X509 certificate whose public key can be successfully used to validate the document signature. Unlike calling the method with the `verifySignatureOnly` parameter set to `false`, no revocation check is performed, no chain trust is checked, and no expiration is verified. Even if your application extracts the certificate itself and passes it to the method with the `verifySignatureOnly` parameter set to `false`, that is still not sufficient validation to prevent document tampering. The certificate still needs to be verified as being appropriate for the document being signed. - -Using an embedded signing certificate can provide useful key rotation strategies, whether in the `` section or in the document content. When using this approach an application should extract the certificate manually and perform validation similar to: - -- The certificate was issued directly or via a chain by a Certificate Authority (CA) whose public certificate is embedded in the application. - - Using the OS-provided trust list without additional checks, such as a known subject name, is not sufficient to prevent tampering in . - -- The certificate is verified to have not been expired at the time of document signing (or "now" for near real-time document processing). - -- For long-lived certificates issued by a CA which supports revocation, verify the certificate was not revoked. - -- The certificate subject is verified as being appropriate to the current document. - -## Choosing the transform algorithm - -If you are interoperating with a specification which has dictated specific values (such as XrML), then you need to follow the specification. If you have an enveloped signature (such as when signing the whole document), then you need to use (represented by the class). You can specify the implicit XML-C14N transform as well, but it's not necessary. For an enveloping or detached signature, no transforms are required. The implicit XML-C14N transform takes care of everything. - -With the security updated introduced by the [Microsoft Security Bulletin MS16-035](/security-updates/securitybulletins/2016/ms16-035), .NET has restricted what transforms can be used in document verification by default, with untrusted transforms causing to always return `false`. In particular, transforms which require additional input (specified as child elements in the XML) are no longer allowed due to their susceptibility of abuse by malicious users. The W3C advises avoiding the XPath and XSLT transforms, which are the two main transforms affected by these restrictions. - -## The problem with external references - -If an application does not verify that external references seem appropriate for the current context, they can be abused in ways that provide for many security vulnerabilities (including Denial of Service, Distributed Reflection Denial of Service, Information Disclosure, Signature Bypass, and Remote Code Execution). Even if an application were to validate the external reference URI, there would remain a problem of the resource being loaded twice: once when your application reads it, and once when reads it. Since there's no guarantee that the application read and document verify steps have the same content, the signature does not provide trustworthiness. - -Given the risks of external references, will throw an exception when an external reference is encountered. For more information about this issue, see [.NET Framework applications encounter exception errors](https://support.microsoft.com/topic/after-you-apply-security-update-3141780-net-framework-applications-encounter-exception-errors-or-unexpected-failures-while-processing-files-that-contain-signedxml-922edd45-a91e-c755-bb30-2604acf37362). diff --git a/docs/fundamentals/runtime-libraries/system-security-securestring.md b/docs/fundamentals/runtime-libraries/system-security-securestring.md deleted file mode 100644 index 274e517858158..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-security-securestring.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: System.Security.SecureString class -description: Learn about the System.Security.SecureString class. -ms.date: 12/31/2023 ---- -# System.Security.SecureString class - -> [!IMPORTANT] -> We recommend that you don't use the `SecureString` class for new development on .NET (Core) or when you migrate existing code to .NET (Core). For more information, see [SecureString shouldn't be used](https://github.com/dotnet/platform-compat/blob/master/docs/DE0001.md). - -[!INCLUDE [context](includes/context.md)] - - is a string type that provides a measure of security. It tries to avoid storing potentially sensitive strings in process memory as plain text. (For limitations, however, see the [How secure is SecureString?](#how-secure-is-securestring) section.) The value of an instance of is automatically protected using a mechanism supported by the underlying platform when the instance is initialized or when the value is modified. Your application can render the instance immutable and prevent further modification by invoking the method. - -The maximum length of a instance is 65,536 characters. - -> [!IMPORTANT] -> This type implements the interface. When you have finished using an instance of the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. - -The class and its members are not visible to COM. For more information, see . - -## String versus SecureString - -An instance of the class is both immutable and, when no longer needed, cannot be programmatically scheduled for garbage collection; that is, the instance is read-only after it is created, and it is not possible to predict when the instance will be deleted from computer memory. Because instances are immutable, operations that appear to modify an existing instance actually create a copy of it to manipulate. Consequently, if a object contains sensitive information such as a password, credit card number, or personal data, there is a risk the information could be revealed after it is used because your application cannot delete the data from computer memory. - -A object is similar to a object in that it has a text value. However, the value of a object is pinned in memory, may use a protection mechanism, such as encryption, provided by the underlying operating system, can be modified until your application marks it as read-only, and can be deleted from computer memory either by your application calling the method or by the .NET garbage collector. - -For a discussion of the limitations of the class, see the [How secure is SecureString?](#how-secure-is-securestring) section. - -## SecureString operations - -The class includes members that allow you to do the following: - -Instantiate a object -You instantiate a object by calling its parameterless constructor. - -Add characters to a object -You can add a single character at a time to a object by calling its or method. - -> [!IMPORTANT] -> A object should never be constructed from a , because the sensitive data is already subject to the memory persistence consequences of the immutable class. The best way to construct a object is from a character-at-a-time unmanaged source, such as the method. - -Remove characters from a object -You can replace an individual character by calling the method, remove an individual character by calling the method, or remove all characters from the instance by calling the method. - -Make the object read-only -Once you have defined the string that the object represents, you call its method to make the string read-only. - -Get information about the object -The class has only two members that provide information about the string: its property, which indicates the number of UTF16-encoded code units in the string; and the , method, which indicates whether the instance is read-only. - -Release the memory allocated to the instance -Because implements the interface, you release its memory by calling the method. - -The class has no members that inspect, compare, or convert the value of a . The absence of such members helps protect the value of the instance from accidental or malicious exposure. Use appropriate members of the class, such as the method, to manipulate the value of a object. - -The .NET Class Library commonly uses instances in the following ways: - -- To provide password information to a process by using the structure or by calling an overload of the method that has a parameter of type . - -- To provide network password information by calling a class constructor that has a parameter of type or by using the property. - -- To provide password information for SQL Server Authentication by calling the constructor or retrieving the value of the property. - -- To pass a string to unmanaged code. For more information, see the [SecureString and interop](#securestring-and-interop) section. - -## SecureString and interop - -Because the operating system does not directly support , you must convert the value of the object to the required string type before passing the string to a native method. The class has five methods that do this: - -- , which converts the string value to a binary string (BSTR) recognized by COM. - -- and , which copy the string value to an ANSI string in unmanaged memory. - -- and , which copy the string value to a Unicode string in unmanaged memory. - -Each of these methods creates a clear-text string in unmanaged memory. It is the responsibility of the developer to zero out and free that memory as soon as it is no longer needed. Each of the string conversion and memory allocation methods has a corresponding method to zero out and free the allocated memory: - -|Allocation and conversion method|Zero and free method| -|--------------------------------------|--------------------------| -||| -||| -||| -||| -||| - -## How secure is SecureString? - -When created properly, a instance provides more data protection than a . When creating a string from a character-at-a-time source, creates multiple intermediate in memory, whereas creates just a single instance. Garbage collection of objects is non-deterministic. In addition, because its memory is not pinned, the garbage collector will make additional copies of values when moving and compacting memory. In contrast, the memory allocated to a object is pinned, and that memory can be freed by calling the method. - -Although data stored in a instance is more secure than data stored in a instance, there are significant limitations on how secure a instance is. These include: - -Platform - -On the Windows operating system, the contents of a instance's internal character array are encrypted. However, whether because of missing APIs or key management issues, encryption is not available on all platforms. Because of this platform dependency, does not encrypt the internal storage on non-Windows platform. Other techniques are used on those platforms to provide additional protection. - -Duration - -Even if the implementation is able to take advantage of encryption, the plain text assigned to the instance may be exposed at various times: - -- Because Windows doesn't offer a secure string implementation at the operating system level, .NET still has to convert the secure string value to its plain text representation in order to use it. - -- Whenever the value of the secure string is modified by methods such as or , it must be decrypted (that is, converted back to plain text), modified, and then encrypted again. - -- If the secure string is used in an interop call, it must be converted to an ANSI string, a Unicode string, or a binary string (BSTR). For more information, see the [SecureString and interop](#securestring-and-interop) section. - -The time interval for which the instance's value is exposed is merely shortened in comparison to the class. - -Storage versus usage -More generally, the class defines a storage mechanism for string values that should be protected or kept confidential. However, outside of .NET itself, no usage mechanism supports . This means that the secure string must be converted to a usable form (typically a clear text form) that can be recognized by its target, and that decryption and conversion must occur in user space. - -Overall, is more secure than because it limits the exposure of sensitive string data. However, those strings may still be exposed to any process or operation that has access to raw memory, such as a malicious process running on the host computer, a process dump, or a user-viewable swap file. Instead of using to protect passwords, the recommended alternative is to use an opaque handle to credentials that are stored outside of the process. diff --git a/docs/fundamentals/runtime-libraries/system-single-compareto.md b/docs/fundamentals/runtime-libraries/system-single-compareto.md deleted file mode 100644 index 77afb3c1e2c23..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-single-compareto.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: System.Single.CompareTo methods -description: Learn about the System.Single.CompareTo methods. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Single.CompareTo methods - -[!INCLUDE [context](includes/context.md)] - -Values must be identical to be considered equal. Particularly when floating-point values depend on multiple mathematical operations, it's common for them to lose precision and for their values to be nearly identical except for their least significant digits. Because of this, the return value of the method may seem surprising at times. For example, multiplication by a particular value followed by division by the same value should produce the original value, but in the following example, the computed value turns out to be greater than the original value. Showing all significant digits of the two values by using the "R" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) indicates that the computed value differs from the original value in its least significant digits. For information about handling such comparisons, see the Remarks section of the method. - -Although an object whose value is is not considered equal to another object whose value is (even itself), the interface requires that `A.CompareTo(A)` return zero. - -## CompareTo(System.Object) - -The `value` parameter must be `null` or an instance of ; otherwise, an exception is thrown. Any instance of , regardless of its value, is considered greater than `null`. - -:::code language="csharp" source="./snippets/System/Single/CompareTo/csharp/compareto3.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Single/CompareTo/fsharp/compareto3.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Single/CompareTo/vb/compareto3.vb" id="Snippet2"::: - -This method is implemented to support the interface. - -## CompareTo(System.Single) - -This method implements the interface and performs slightly better than the overload because it doesn't have to convert the `value` parameter to an object. - -:::code language="csharp" source="./snippets/System/Single/CompareTo/csharp/compareto2.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Single/CompareTo/fsharp/compareto2.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Single/CompareTo/vb/compareto2.vb" id="Snippet1"::: - -## Widening conversions - -Depending on your programming language, it might be possible to code a method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. - -For example, suppose the instance type is and the parameter type is . The Microsoft C# compiler generates instructions to represent the value of the parameter as a object, then generates a method that compares the values of the instance and the widened representation of the parameter. - -Consult your programming language's documentation to determine if its compiler performs implicit widening conversions of numeric types. For more information, see the [Type Conversion Tables](../../standard/base-types/conversion-tables.md) topic. - -## Precision in comparisons - -The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of .NET. Consequently, a comparison of two particular numbers might change between versions of .NET because the precision of the numbers' internal representation might change. diff --git a/docs/fundamentals/runtime-libraries/system-single-epsilon.md b/docs/fundamentals/runtime-libraries/system-single-epsilon.md deleted file mode 100644 index 5dad574c61ef6..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-single-epsilon.md +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: System.Single.Epsilon property -description: Learn about the System.Single.Epsilon property. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Single.Epsilon property - -[!INCLUDE [context](includes/context.md)] - -The value of the property reflects the smallest positive value that is significant in numeric operations or comparisons when the value of the instance is zero. For example, the following code shows that zero and are considered to be unequal values, whereas zero and half the value of are considered to be equal. - -:::code language="csharp" source="./snippets/System/Single/Epsilon/csharp/epsilon.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/Single/Epsilon/fsharp/epsilon.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/Single/Epsilon/vb/epsilon.vb" id="Snippet5"::: - -More precisely, the single-precision floating-point format consists of a sign, a 23-bit mantissa or significand, and an 8-bit exponent. As the following example shows, zero has an exponent of -126 and a mantissa of 0. has an exponent of -126 and a mantissa of 1. This means that is the smallest positive value that is greater than zero and represents the smallest possible value and the smallest possible increment for a whose exponent is -126. - -:::code language="csharp" source="./snippets/System/Single/Epsilon/csharp/epsilon1.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System/Single/Epsilon/fsharp/epsilon1.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System/Single/Epsilon/vb/epsilon1.vb" id="Snippet6"::: - -However, the property is not a general measure of precision of the type; it applies only to instances that have a value of zero. - -> [!NOTE] -> The value of the property is not equivalent to machine epsilon, which represents the upper bound of the relative error due to rounding in floating-point arithmetic. - -The value of this constant is 1.4e-45. - -Two apparently equivalent floating-point numbers might not compare equal because of differences in their least significant digits. For example, the C# expression, `(float)1/3 == (float)0.33333`, does not compare equal because the division operation on the left side has maximum precision while the constant on the right side is precise only to the specified digits. If you create a custom algorithm that determines whether two floating-point numbers can be considered equal, you must use a value that is greater than the constant to establish the acceptable absolute margin of difference for the two values to be considered equal. (Typically, that margin of difference is many times greater than .) - -## Platform notes - -On ARM systems, the value of the constant is too small to be detected, so it equates to zero. You can define an alternative epsilon value that equals 1.175494351E-38 instead. diff --git a/docs/fundamentals/runtime-libraries/system-single-equals.md b/docs/fundamentals/runtime-libraries/system-single-equals.md deleted file mode 100644 index 81b554ed638fc..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-single-equals.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: System.Single.Equals method -description: Learn about the System.Single.Equals method. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Single.Equals method - -[!INCLUDE [context](includes/context.md)] - -The method implements the interface, and performs slightly better than because it does not have to convert the `obj` parameter to an object. - -## Widening conversions - -Depending on your programming language, it might be possible to code an method where the parameter type has fewer bits (is narrower) than the instance type. This is possible because some programming languages perform an implicit widening conversion that represents the parameter as a type with as many bits as the instance. - -For example, suppose the instance type is and the parameter type is . The Microsoft C# compiler generates instructions to represent the value of the parameter as a object, and then generates a method that compares the values of the instance and the widened representation of the parameter. - -Consult your programming language's documentation to determine if its compiler performs implicit widening conversions of numeric types. For more information, see [Type Conversion Tables](../../standard/base-types/conversion-tables.md). - -## Precision in comparisons - -The method should be used with caution, because two apparently equivalent values can be unequal because of the differing precision of the two values. The following example reports that the value .3333 and the returned by dividing 1 by 3 are unequal. - -:::code language="csharp" source="./snippets/System/Single/Epsilon/csharp/SingleEquals_25051.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Single/Epsilon/fsharp/SingleEquals_25051.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Single/Epsilon/vb/SingleEquals_25051.vb" id="Snippet1"::: - -One comparison technique that avoids the problems associated with comparing for equality involves defining an acceptable margin of difference between two values (such as .01% of one of the values). If the absolute value of the difference between the two values is less than or equal to that margin, the difference is likely to be an outcome of differences in precision and, therefore, the values are likely to be equal. The following example uses this technique to compare .33333 and 1/3, which are the two values that the previous code example found to be unequal. - -:::code language="csharp" source="./snippets/System/Single/Epsilon/csharp/SingleEquals_25051.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Single/Epsilon/fsharp/SingleEquals_25051.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/Single/Epsilon/vb/SingleEquals_25051.vb" id="Snippet2"::: - -In this case, the values are equal. - -> [!NOTE] -> Because defines the minimum expression of a positive value whose range is near zero, the margin of difference must be greater than . Typically, it is many times greater than . Because of this, we recommend that you do not use when comparing values for equality. - -A second technique that avoids the problems associated with comparing for equality involves comparing the difference between two floating-point numbers with some absolute value. If the difference is less than or equal to that absolute value, the numbers are equal. If it is greater, the numbers are not equal. One way to do this is to arbitrarily select an absolute value. However, this is problematic, because an acceptable margin of difference depends on the magnitude of the values. A second way takes advantage of a design feature of the floating-point format: The difference between the mantissa components in the integer representations of two floating-point values indicates the number of possible floating-point values that separates the two values. For example, the difference between 0.0 and is 1, because is the smallest representable value when working with a whose value is zero. The following example uses this technique to compare .33333 and 1/3, which are the two values that the previous code example with the method found to be unequal. Note that the example uses the and methods to convert a single-precision floating-point value to its integer representation. - -:::code language="csharp" source="./snippets/System/Single/Equals/csharp/equalsabs1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Single/Equals/fsharp/equalsabs1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/Single/Equals/vb/equalsabs1.vb" id="Snippet1"::: - -The precision of floating-point numbers beyond the documented precision is specific to the implementation and version of .NET. Consequently, a comparison of two numbers might produce different results depending on the version of .NET, because the precision of the numbers' internal representation might change. diff --git a/docs/fundamentals/runtime-libraries/system-single.md b/docs/fundamentals/runtime-libraries/system-single.md deleted file mode 100644 index e3aac6130214b..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-single.md +++ /dev/null @@ -1,223 +0,0 @@ ---- -title: System.Single struct -description: Learn about the System.Single struct. -ms.date: 01/23/2026 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Single struct - -[!INCLUDE [context](includes/context.md)] - -The value type represents a single-precision 32-bit number with values ranging from negative 3.402823e38 to positive 3.402823e38, as well as positive or negative zero, , , and not a number (). It is intended to represent values that are extremely large (such as distances between planets or galaxies) or extremely small (such as the molecular mass of a substance in kilograms) and that often are imprecise (such as the distance from earth to another solar system). The type complies with the IEC 60559:1989 (IEEE 754) standard for binary floating-point arithmetic. - - provides methods to compare instances of this type, to convert the value of an instance to its string representation, and to convert the string representation of a number to an instance of this type. For information about how format specification codes control the string representation of value types, see [Formatting Types](../../standard/base-types/formatting-types.md), [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md), and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md). - -## Floating-point representation and precision - -The data type stores single-precision floating-point values in a 32-bit binary format, as shown in the following table: - -| Part | Bits | -|-----------------------------------|-------| -| Significand or mantissa | 0-22 | -| Exponent | 23-30 | -| Sign (0 = positive, 1 = negative) | 31 | - -Just as decimal fractions are unable to precisely represent some fractional values (such as 1/3 or ), binary fractions are unable to represent some fractional values. For example, 2/10, which is represented precisely by .2 as a decimal fraction, is represented by .0011111001001100 as a binary fraction, with the pattern "1100" repeating to infinity. In this case, the floating-point value provides an imprecise representation of the number that it represents. Performing additional mathematical operations on the original floating-point value often increases its lack of precision. For example, if you compare the results of multiplying .3 by 10 and adding .3 to .3 nine times, you will see that addition produces the less precise result, because it involves eight more operations than multiplication. Note that this disparity is apparent only if you display the two values by using the "R" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md), which, if necessary, displays all 9 digits of precision supported by the type. - -:::code language="csharp" source="./snippets/System/Single/Overview/csharp/representation1.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/representation1.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/Single/Overview/vb/representation1.vb" id="Snippet3"::: - -Because some numbers cannot be represented exactly as fractional binary values, floating-point numbers can only approximate real numbers. - -All floating-point numbers have a limited number of significant digits, which also determines how accurately a floating-point value approximates a real number. A value has up to 7 decimal digits of precision, although a maximum of 9 digits is maintained internally. This means that some floating-point operations may lack the precision to change a floating-point value. The following example defines a large single-precision floating-point value, and then adds the product of and one quadrillion to it. However, the product is too small to modify the original floating-point value. Its least significant digit is thousandths, whereas the most significant digit in the product is 10-30. - -:::code language="csharp" source="./snippets/System/Single/Overview/csharp/representation2.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/representation2.fs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/Single/Overview/vb/representation2.vb" id="Snippet4"::: - -The limited precision of a floating-point number has several consequences: - -- Two floating-point numbers that appear equal for a particular precision might not compare equal because their least significant digits are different. In the following example, a series of numbers are added together, and their total is compared with their expected total. A call to the `Equals` method indicates that the values aren't equal. - - :::code language="csharp" source="./snippets/System/Single/Overview/csharp/precisionlist3.cs" id="Snippet6"::: - :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/precisionlist3.fs" id="Snippet6"::: - :::code language="vb" source="./snippets/System/Single/Overview/vb/precisionlist3.vb" id="Snippet6"::: - - The two values are unequal because of a loss of precision during the addition operations. In this case, the issue can be resolved by calling the method to round the values to the desired precision before performing the comparison. - -- A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used, because the binary floating-point number might not equal the decimal number. A previous example illustrated this by displaying the result of multiplying .3 by 10 and adding .3 to .3 nine times. - - When accuracy in numeric operations with fractional values is important, use the type instead of the type. When accuracy in numeric operations with integral values beyond the range of the or types is important, use the type. - -- A value might not *round-trip* if a floating-point number is involved. A value is said to round-trip if an operation converts an original floating-point number to another form, an inverse operation transforms the converted form back to a floating-point number, and the final floating-point number is equal to the original floating-point number. The round trip might fail because one or more least significant digits are lost or changed in a conversion. - - In the following example, three values are converted to strings and saved in a file. If you run this example on .NET Framework, even though the values appear to be identical, the restored values are not equal to the original values. (This has since been addressed in .NET, where the values round-trip correctly.) - - :::code language="csharp" source="./snippets/System/Single/Overview/csharp/precisionlist4a.cs" id="Snippet17"::: - :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/precisionlist4a.fs" id="Snippet17"::: - :::code language="vb" source="./snippets/System/Single/Overview/vb/PrecisionList4a.vb" id="Snippet17"::: - - If you're targeting .NET Framework, the values can be successfully round-tripped by using the "G9" [standard numeric format string](../../standard/base-types/standard-numeric-format-strings.md) to preserve the full precision of values. - -- values have less precision than values. A value that is converted to a seemingly equivalent often does not equal the value because of differences in precision. In the following example, the result of identical division operations is assigned to a value and a value. After the value is cast to a , a comparison of the two values shows that they are unequal. - - :::code language="csharp" source="./snippets/System/Double/Overview/csharp/precisionlist1.cs" id="Snippet5"::: - :::code language="fsharp" source="./snippets/System/Double/Overview/fsharp/precisionlist1.fs" id="Snippet5"::: - :::code language="vb" source="./snippets/System/Double/Overview/vb/precisionlist1.vb" id="Snippet5"::: - - To avoid this problem, either use the data type in place of the data type, or use the method so that both values have the same precision. - -## Test for equality - -To be considered equal, two values must represent identical values. However, because of differences in precision between values, or because of a loss of precision by one or both values, floating-point values that are expected to be identical often turn out to be unequal due to differences in their least significant digits. As a result, calls to the method to determine whether two values are equal, or calls to the method to determine the relationship between two values, often yield unexpected results. This is evident in the following example, where two apparently equal values turn out to be unequal, because the first value has 7 digits of precision, whereas the second value has 9. - -:::code language="csharp" source="./snippets/System/Single/Overview/csharp/comparison1.cs" id="Snippet9"::: -:::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/comparison1.fs" id="Snippet9"::: -:::code language="vb" source="./snippets/System/Single/Overview/vb/comparison1.vb" id="Snippet9"::: - -Calculated values that follow different code paths and that are manipulated in different ways often prove to be unequal. In the following example, one value is squared, and then the square root is calculated to restore the original value. A second is multiplied by 3.51 and squared before the square root of the result is divided by 3.51 to restore the original value. Although the two values appear to be identical, a call to the method indicates that they are not equal. - -:::code language="csharp" source="./snippets/System/Single/Overview/csharp/comparison2.cs" id="Snippet10"::: -:::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/comparison2.fs" id="Snippet10"::: -:::code language="vb" source="./snippets/System/Single/Overview/vb/comparison2.vb" id="Snippet10"::: - -In cases where a loss of precision is likely to affect the result of a comparison, you can use the following techniques instead of calling the or method: - -- Call the method to ensure that both values have the same precision. The following example modifies a previous example to use this approach so that two fractional values are equivalent. - - :::code language="csharp" source="./snippets/System/Single/Overview/csharp/comparison3.cs" id="Snippet11"::: - :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/comparison3.fs" id="Snippet11"::: - :::code language="vb" source="./snippets/System/Single/Overview/vb/comparison3.vb" id="Snippet11"::: - - The problem of precision still applies to rounding of midpoint values. For more information, see the method. - -- Test for approximate equality instead of equality. This technique requires that you define either an absolute amount by which the two values can differ but still be equal, or that you define a relative amount by which the smaller value can diverge from the larger value. - - > [!WARNING] - > is sometimes used as an absolute measure of the distance between two values when testing for equality. However, measures the smallest possible value that can be added to, or subtracted from, a whose value is zero. For most positive and negative values, the value of is too small to be detected. Therefore, except for values that are zero, we do not recommend its use in tests for equality. - - The following example uses the latter approach to define an `IsApproximatelyEqual` method that tests the relative difference between two values. It also contrasts the result of calls to the `IsApproximatelyEqual` method and the method. - - :::code language="csharp" source="./snippets/System/Single/Overview/csharp/comparison4.cs" id="Snippet12"::: - :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/comparison4.fs" id="Snippet12"::: - :::code language="vb" source="./snippets/System/Single/Overview/vb/comparison4.vb" id="Snippet12"::: - -## Floating-point values and exceptions - -Operations with floating-point values do not throw exceptions, unlike operations with integral types, which throw exceptions in cases of illegal operations such as division by zero or overflow. Instead, in these situations, the result of a floating-point operation is zero, positive infinity, negative infinity, or not a number (NaN): - -- If the result of a floating-point operation is too small for the destination format, the result is zero. This can occur when two very small floating-point numbers are multiplied, as the following example shows. - - :::code language="csharp" source="./snippets/System/Single/Overview/csharp/exceptional1.cs" id="Snippet1"::: - :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/exceptional1.fs" id="Snippet1"::: - :::code language="vb" source="./snippets/System/Single/Overview/vb/exceptional1.vb" id="Snippet1"::: - -- If the magnitude of the result of a floating-point operation exceeds the range of the destination format, the result of the operation is or , as appropriate for the sign of the result. The result of an operation that overflows is , and the result of an operation that overflows is , as the following example shows. - - :::code language="csharp" source="./snippets/System/Single/Overview/csharp/exceptional2.cs" id="Snippet2"::: - :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/exceptional2.fs" id="Snippet2"::: - :::code language="vb" source="./snippets/System/Single/Overview/vb/exceptional2.vb" id="Snippet2"::: - - also results from a division by zero with a positive dividend, and results from a division by zero with a negative dividend. - -- If a floating-point operation is invalid, the result of the operation is . For example, results from the following operations: - - - Division by zero with a dividend of zero. Note that other cases of division by zero result in either or . - - Any floating-point operation with invalid input. For example, attempting to find the square root of a negative value returns . - - Any operation with an argument whose value is . - -## Type conversions - -The structure does not define any explicit or implicit conversion operators; instead, conversions are implemented by the compiler. - -The following table lists the possible conversions of a value of the other primitive numeric types to a value. It also indicates whether the conversion is widening or narrowing and whether the resulting may have less precision than the original value. - -| Conversion from | Widening/narrowing | Possible loss of precision | -|---------------------|--------------------|----------------------------| -| | Widening | No | -||Widening

Note that C# requires a cast operator.|Yes. supports 29 decimal digits of precision; supports 9.| -||Narrowing; out-of-range values are converted to or .|Yes. supports 17 decimal digits of precision; supports 9.| -| | Widening | No | -||Widening|Yes. supports 10 decimal digits of precision; supports 9.| -||Widening|Yes. supports 19 decimal digits of precision; supports 9.| -||Widening|No| -||Widening|No| -||Widening|Yes. supports 10 decimal digits of precision; supports 9.| -||Widening|Yes. supports 20 decimal digits of precision; supports 9.| - -The following example converts the minimum or maximum value of other primitive numeric types to a value. - -:::code language="csharp" source="./snippets/System/Single/Overview/csharp/convert1.cs" id="Snippet20"::: -:::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/convert1.fs" id="Snippet20"::: -:::code language="vb" source="./snippets/System/Single/Overview/vb/convert1.vb" id="Snippet20"::: - -In addition, the values , , and convert to , , and , respectively. - -Note that the conversion of the value of some numeric types to a value can involve a loss of precision. As the example illustrates, a loss of precision is possible when converting , , , , , and values to values. - -The conversion of a value to a is a widening conversion. The conversion may result in a loss of precision if the type does not have a precise representation for the value. - -The conversion of a value to a value of any primitive numeric data type other than a is a narrowing conversion and requires a cast operator (in C#) or a conversion method (in Visual Basic). Values that are outside the range of the target data type, which are defined by the target type's `MinValue` and `MaxValue` properties, behave as shown in the following table. - -| Target type | Result | -|-----------------------|-----------------------------------------------| -| Any integral type | An exception if the conversion occurs in a checked context.

If the conversion occurs in an unchecked context (the default in C#), the conversion operation succeeds but the value overflows. | -| | An exception. | - -In addition, , , and throw an for conversions to integers in a checked context, but these values overflow when converted to integers in an unchecked context. For conversions to , they always throw an . For conversions to , they convert to , , and , respectively. - -Note that a loss of precision may result from converting a value to another numeric type. In the case of converting non-integral values, as the output from the example shows, the fractional component is lost when the value is either rounded (as in Visual Basic) or truncated (as in C# and F#). For conversions to values, the value may not have a precise representation in the target data type. - -The following example converts a number of values to several other numeric types. The conversions occur in a checked context in Visual Basic (the default), in C# (because of the [checked](/dotnet/csharp/language-reference/keywords/checked) keyword), and in F# (because of the `open Checked` statement). The output from the example shows the result for conversions in both a checked an unchecked context. You can perform conversions in an unchecked context in Visual Basic by compiling with the `/removeintchecks+` compiler switch, in C# by commenting out the `checked` statement, and in F# by commenting out the `open Checked` statement. - -:::code language="csharp" source="./snippets/System/Single/Overview/csharp/convert2.cs" id="Snippet21"::: -:::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/convert2.fs" id="Snippet21"::: -:::code language="vb" source="./snippets/System/Single/Overview/vb/convert2.vb" id="Snippet21"::: - -For more information on the conversion of numeric types, see [Type Conversion in .NET](../../standard/base-types/type-conversion.md) and [Type Conversion Tables](../../standard/base-types/conversion-tables.md). - -## Floating-point functionality - -The structure and related types provide methods to perform the following categories of operations: - -- **Comparison of values**. You can call the method to determine whether two values are equal, or the method to determine the relationship between two values. - - The structure also supports a complete set of comparison operators. For example, you can test for equality or inequality, or determine whether one value is greater than or equal to another value. If one of the operands is a , the value is converted to a before performing the comparison. If one of the operands is an integral type, it is converted to a before performing the comparison. Although these are widening conversions, they may involve a loss of precision. - - > [!WARNING] - > Because of differences in precision, two values that you expect to be equal may turn out to be unequal, which affects the result of the comparison. See the [Test for equality](#test-for-equality) section for more information about comparing two values. - - You can also call the , , , and methods to test for these special values. - -- **Mathematical operations**. Common arithmetic operations such as addition, subtraction, multiplication, and division are implemented by language compilers and Common Intermediate Language (CIL) instructions rather than by methods. If the other operand in a mathematical operation is a , the is converted to a before performing the operation, and the result of the operation is also a value. If the other operand is an integral type, it is converted to a before performing the operation, and the result of the operation is also a value. - - You can perform other mathematical operations by calling `static` (`Shared` in Visual Basic) methods in the class. These include additional methods commonly used for arithmetic (such as , , and ), geometry (such as and ), and calculus (such as ). In all cases, the value is converted to a . - - You can also manipulate the individual bits in a value. The method returns its bit pattern in a byte array. By passing that byte array to the method, you can also preserve the value's bit pattern in a 32-bit integer. - -- **Rounding**. Rounding is often used as a technique for reducing the impact of differences between values caused by problems of floating-point representation and precision. You can round a value by calling the method. However, note that the value is converted to a before the method is called, and the conversion can involve a loss of precision. - -- **Formatting**. You can convert a value to its string representation by calling the method or by using the [composite formatting](../../standard/base-types/composite-formatting.md) feature. For information about how format strings control the string representation of floating-point values, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md). - -- **Parsing strings**. You can convert the string representation of a floating-point value to a value by calling the or method. If the parse operation fails, the method throws an exception, whereas the method returns `false`. - -- **Type conversion**. The structure provides an explicit interface implementation for the interface, which supports conversion between any two standard .NET data types. Language compilers also support the implicit conversion of values for all other standard numeric types except for the conversion of to values. Conversion of a value of any standard numeric type other than a to a is a widening conversion and does not require the use of a casting operator or conversion method. - - However, conversion of 32-bit and 64-bit integer values can involve a loss of precision. The following table lists the differences in precision for 32-bit, 64-bit, and types: - - | Type | Maximum precision (decimal digits) | Internal precision (decimal digits) | - |----------------------|------------------------------------|-------------------------------------| - | | 15 | 17 | - | and | 10 | 10 | - | and | 19 | 19 | - | | 7 | 9 | - - The problem of precision most frequently affects values that are converted to values. In the following example, two values produced by identical division operations are unequal, because one of the values is a single-precision floating point value that is converted to a . - - :::code language="csharp" source="./snippets/System/Single/Overview/csharp/precisionlist1.cs" id="Snippet5"::: - :::code language="fsharp" source="./snippets/System/Single/Overview/fsharp/precisionlist1.fs" id="Snippet5"::: - :::code language="vb" source="./snippets/System/Single/Overview/vb/precisionlist1.vb" id="Snippet5"::: diff --git a/docs/fundamentals/runtime-libraries/system-span{t}.md b/docs/fundamentals/runtime-libraries/system-span{t}.md deleted file mode 100644 index 83204b6b17b3e..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-span{t}.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: System.Span struct -description: Learn about the System.Span\ struct. -ms.date: 05/21/2025 -dev_langs: - - CSharp - - FSharp ---- -# System.Span\ struct - -[!INCLUDE [context](includes/context.md)] - -The type is a [ref struct](../../csharp/language-reference/builtin-types/ref-struct.md) that is allocated on the stack rather than on the managed heap. Ref struct types have a number of restrictions to ensure that they cannot be promoted to the managed heap, including that they can't be boxed, they can't be assigned to variables of type , `dynamic` or to any interface type, they can't be fields in a reference type, and they can't be used across `await` and `yield` boundaries. In addition, calls to two methods, and , throw a . - -> [!IMPORTANT] -> Because it is a stack-only type, `Span` is unsuitable for many scenarios that require storing references to buffers on the heap. This is true, for example, of routines that make asynchronous method calls. For such scenarios, you can use the complementary and types. - -For spans that represent immutable or read-only structures, use . - -## Memory - -A `Span` represents a contiguous region of arbitrary memory. A `Span` instance is often used to hold the elements of an array or a portion of an array. Unlike an array, however, a `Span` instance can point to managed memory, native memory, or memory managed on the stack. The following example creates a `Span` from an array: - -:::code language="csharp" source="./snippets/System/Span/Overview/csharp/program.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/Span/Overview/fsharp/program.fs" id="Snippet1"::: - -The following example creates a `Span` from 100 bytes of native memory: - -:::code language="csharp" source="./snippets/System/Span/Overview/csharp/program.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/Span/Overview/fsharp/program.fs" id="Snippet2"::: - -The following example uses the C# [stackalloc](/dotnet/csharp/language-reference/keywords/stackalloc) keyword to allocate 100 bytes of memory on the stack: - -:::code language="csharp" source="./snippets/System/Span/Overview/csharp/program.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/Span/Overview/fsharp/program.fs" id="Snippet3"::: - -Because `Span` is an abstraction over an arbitrary block of memory, methods of the `Span` type and methods with `Span` parameters operate on any `Span` object regardless of the kind of memory it encapsulates. For example, each of the separate sections of code that initialize the span and calculate the sum of its elements can be refactored into single initialization and calculation methods, as the following example illustrates: - -:::code language="csharp" source="./snippets/System/Span/Overview/csharp/program.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/Span/Overview/fsharp/program.fs" id="Snippet4"::: - -## Arrays - -When it wraps an array, `Span` can wrap an entire array, as it did in the examples in the [Memory](#memory) section. Because it supports slicing, `Span` can also point to any contiguous range within the array. - -The following example creates a slice of the middle five elements of a 10-element integer array. Note that the code doubles the values of each integer in the slice. As the output shows, the changes made by the span are reflected in the values of the array. - -:::code language="csharp" source="./snippets/System/Span/Slice/csharp/Program.cs"::: -:::code language="fsharp" source="./snippets/System/Span/Slice/fsharp/Program.fs"::: - -## Slices - -`Span` includes two overloads of the method that form a slice out of the current span that starts at a specified index. This makes it possible to treat the data in a `Span` as a set of logical chunks that can be processed as needed by portions of a data processing pipeline with minimal performance impact. For example, since modern server protocols are often text-based, manipulation of strings and substrings is particularly important. In the class, the major method for extracting substrings is . For data pipelines that rely on extensive string manipulation, its use offers some performance penalties, since it: - -1. Creates a new string to hold the substring. -2. Copies a subset of the characters from the original string to the new string. - -This allocation and copy operation can be eliminated by using either `Span` or , as the following example shows: - -:::code language="csharp" source="./snippets/System/Span/Slice/csharp/Program2.cs"::: -:::code language="fsharp" source="./snippets/System/Span/Slice/fsharp/Program2.fs"::: diff --git a/docs/fundamentals/runtime-libraries/system-string-ctor.md b/docs/fundamentals/runtime-libraries/system-string-ctor.md deleted file mode 100644 index 03aed4d786242..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-string-ctor.md +++ /dev/null @@ -1,190 +0,0 @@ ---- -title: System.String constructor -description: Learn about the System.String constructor. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp ---- -# System.String constructor - -[!INCLUDE [context](includes/context.md)] - -## Overloaded constructor syntax - -[String constructors](xref:System.String.%23ctor%2A) fall into two categories: those without pointer parameters, and those with pointer parameters. The constructors that use pointers are not CLS-compliant. In addition, Visual Basic does not support the use of pointers, and C# requires code that uses pointers to run in an unsafe context. For more information, see [unsafe](../../csharp/language-reference/keywords/unsafe.md). - -For additional guidance on choosing an overload, see [Which method do I call?](#which-method-do-i-call). - -`String(Char[] value)`\ -Initializes the new instance to the value indicated by an array of Unicode characters. This constructor copies Unicode characters([Example 2: Use a character array](#example-2-use-a-character-array)). - -`String(Char[] value, Int32 startIndex, Int32 length)`\ -Initializes the new instance to the value indicated by an array of Unicode characters, a starting character position within that array, and a length ([Example 3: Use a portion of a character array and repeating a single character](#example-3-use-a-portion-of-a-character-array-and-repeating-a-single-character)). - -`String(Char c, Int32 count)`\ -Initializes the new instance to the value indicated by a specified Unicode character repeated a specified number of times ([Example 3: Use a portion of a character array and repeating a single character](#example-3-use-a-portion-of-a-character-array-and-repeating-a-single-character)). - -`String(char* value)`\ -**(Not CLS-compliant)** Initializes the new instance to the value indicated by a pointer to an array of Unicode characters that is terminated by a null character (U+0000 or '\0'). ([Example 4: Use a pointer to a character array](#example-4-use-a-pointer-to-a-character-array)). - -Permission: , requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code. - -`String(char* value, Int32 startIndex, Int32 length)`\ -**(Not CLS-compliant)** Initializes the new instance to the value indicated by a pointer to an array of Unicode characters, a starting character position within that array, and a length. The constructor copies the Unicode characters from `value` starting at index `startIndex` and ending at index `startIndex` + `length` - 1 ([Example 5: Instantiate a string from a pointer and a range of an array](#example-5-instantiate-a-string-from-a-pointer-and-a-range-of-an-array)). - -Permission: , requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code. - -`String(SByte* value)`\ -**(Not CLS-compliant)** Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers. The array is assumed to represent a string encoded using the current system code page (that is, the encoding specified by ). The constructor processes characters from `value` starting from the location specified by the pointer until a null character (0x00) is reached ([Example 6: Instantiate a string from a pointer to a signed byte array](#example-6-instantiate-a-string-from-a-pointer-to-a-signed-byte-array)). - -Permission: , requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code. - -`String(SByte* value, Int32 startIndex, Int32 length)`\ -**(Not CLS-compliant)** Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers, a starting position within that array, and a length. The array is assumed to represent a string encoded using the current system code page (that is, the encoding specified by ). The constructor processes characters from value starting at `startIndex` and ending at `startIndex` + `length` - 1 ([Example 6: Instantiate a string from a pointer to a signed byte array](#example-6-instantiate-a-string-from-a-pointer-to-a-signed-byte-array)). - -Permission: , requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code. - -`String(SByte* value, Int32 startIndex, Int32 length, Encoding enc)`\ -**(Not CLS-compliant)** Initializes the new instance to the value indicated by a pointer to an array of 8-bit signed integers, a starting position within that array, a length, and an object. - -Permission: , requires full trust for the immediate caller. This member cannot be used by partially trusted or transparent code. - -## Parameters - -Here is a complete list of parameters used by constructors that don't include a pointer parameter. For the parameters used by each overload, see the overload syntax above. - -| Parameter | Type | Description | -|-----------|----------------------|---------------------------------| -| `value` | [] | An array of Unicode characters. | -| `c` | | A Unicode character. | -| `startIndex` | |The starting position in `value` of the first character in the new string.

Default value: 0| -| `length` | |The number of characters in `value` to include in the new string.

Default value: | -| `count` | |The number of times the character `c` is repeated in the new string. If `count` is zero, the value of the new object is .| - -Here is a complete list of parameters used by constructors that include a pointer parameter. For the parameters used by each overload, see the overload syntax above. - -| Parameter | Type | Description | -|-----------|------|-------------| -|`value`|*

-or-

\*|A pointer to a null-terminated array of Unicode characters or an array of 8-bit signed integers. If `value` is `null` or an empty array, the value of the new string is .| -|`startIndex`||The index of the array element that defines the first character in the new string.

Default value: 0| -|`length`||The number of array elements to use to create the new string. If length is zero, the constructor creates a string whose value is .

Default value: | -|`enc`||An object that specifies how the `value` array is encoded.

Default value: , or the system's current ANSI code page| - -## Exceptions - -Here's a list of exceptions thrown by constructors that don't include pointer parameters. - -| Exception | Condition | Thrown by | -|-----------|-----------|-----------| -||`value` is `null`.|| -||`startIndex`, `length`, or `count` is less than zero.

-or-

The sum of `startIndex` and `length` is greater than the number of elements in `value`.

-or-

`count` is less than zero.|

| - -Here's a list of exceptions thrown by constructors that include pointer parameters. - -| Exception | Condition | Thrown by | -|-----------|-----------|-----------| -||`value` specifies an array that contains an invalid Unicode character.

-or-

`value` or `value` + `startIndex` specifies an address that is less than 64K.

-or-

A new instance could not be initialized from the `value` byte array because `value` does not use the default code page encoding.|All constructors with pointers.| -||`value` is null.|



| -||The current process does not have read access to all the addressed characters.

-or-

`startIndex` or `length` is less than zero, `value` + `startIndex` cause a pointer overflow, or the current process does not have read access to all the addressed characters.

-or-

The length of the new string is too large to allocate.|All constructors with pointers.| -||`value`, or `value` + `startIndex` + `length` - 1, specifies an invalid address.|



| - -## Which method do I call? - -| To | Call or use | -|----|-------------| -|Create a string.|Assignment from a string literal or an existing string ([Example 1: Use string assignment](#example-1-use-string-assignment))| -|Create a string from an entire character array.| ([Example 2: Use a character array](#example-2-use-a-character-array))| -|Create a string from a portion of a character array.| ([Example 3: Use a portion of a character array and repeating a single character](#example-3-use-a-portion-of-a-character-array-and-repeating-a-single-character))| -|Create a string that repeats the same character multiple times.| ([Example 3: Use a portion of a character array and repeating a single character](#example-3-use-a-portion-of-a-character-array-and-repeating-a-single-character))| -|Create a string from a pointer to a Unicode or wide character array.|| -|Create a string from a portion of a Unicode or wide character array by using its pointer.|| -|Create a string from a C++ `char` array.|,

-or-

| -|Create a string from ASCII characters.|| - -## Create strings - -The most commonly used technique for creating strings programmatically is simple assignment, as illustrated in [Example 1](#example-1-use-string-assignment). The class also includes four types of constructor overloads that let you create strings from the following values: - -- From a character array (an array of UTF-16-encoded characters). You can create a new object from the characters in the entire array or a portion of it. The constructor copies all the characters in the array to the new string. The constructor copies the characters from index `startIndex` to index `startIndex` + `length` - 1 to the new string. If `length` is zero, the value of the new string is . - - If your code repeatedly instantiates strings that have the same value, you can improve application performance by using an alternate means of creating strings. For more information, see [Handle repetitive strings](#handle-repetitive-strings). - -- From a single character that is duplicated zero, one, or more times, by using the constructor. If `count` is zero, the value of the new string is . - -- From a pointer to a null-terminated character array, by using the or constructor. Either the entire array or a specified range can be used to initialize the string. The constructor copies a sequence of Unicode characters starting from the specified pointer or from the specified pointer plus `startIndex` and continuing to the end of the array or for `length` characters. If `value` is a null pointer or `length` is zero, the constructor creates a string whose value is . If the copy operation proceeds to the end of the array and the array is not null-terminated, the constructor behavior is system-dependent. Such a condition might cause an access violation. - - If the array contains any embedded null characters (U+0000 or '\0') and the overload is called, the string instance contains `length` characters including any embedded nulls. The following example shows what happens when a pointer to an array of 10 elements that includes two null characters is passed to the method. Because the address is the beginning of the array and all elements in the array are to be added to the string, the constructor instantiates a string with ten characters, including two embedded nulls. On the other hand, if the same array is passed to the constructor, the result is a four-character string that does not include the first null character. - - :::code language="csharp" source="./snippets/System/String/.ctor/csharp/chptrctor_null.cs" id="Snippet5"::: - :::code language="fsharp" source="./snippets/System/String/.ctor/fsharp/chptrctor_null.fs" id="Snippet5"::: - - The array must contain Unicode characters. In C++, this means that the character array must be defined either as the managed [] type or the unmanaged`wchar_t`[] type. - - If the overload is called and the array is not null-terminated, or if the overload is called and `startIndex` + `length`-1 includes a range that is outside the memory allocated for the sequence of characters, the behavior of the constructor is system-dependent, and an access violation may occur. - -- From a pointer to a signed byte array. Either the entire array or a specified range can be used to initialize the string. The sequence of bytes can be interpreted by using the default code page encoding, or an encoding can be specified in the constructor call. If the constructor tries to instantiate a string from an entire array that is not null-terminated, or if the range of the array from `value` + `startIndex` to `value` + `startIndex` + `length` -1 is outside of the memory allocated for the array, the behavior of this constructor is system-dependent, and an access violation may occur. - - The three constructors that include a signed byte array as a parameter are designed primarily to convert a C++ `char` array to a string, as shown in this example: - - :::code language="cpp" source="./snippets/System/String/.ctor/cpp/sbyte_ctor1.cpp" id="Snippet4"::: - - If the array contains any null characters ('\0') or bytes whose value is 0 and the overload is called, the string instance contains `length` characters including any embedded nulls. The following example shows what happens when a pointer to an array of 10 elements that includes two null characters is passed to the method. Because the address is the beginning of the array and all elements in the array are to be added to the string, the constructor instantiates a string with ten characters, including two embedded nulls. On the other hand, if the same array is passed to the constructor, the result is a four-character string that does not include the first null character. - - :::code language="csharp" source="./snippets/System/String/.ctor/csharp/ptrctor_null.cs" id="Snippet6"::: - :::code language="fsharp" source="./snippets/System/String/.ctor/fsharp/ptrctor_null.fs" id="Snippet6"::: - - Because the and constructors interpret `value` by using the default ANSI code page, calling these constructors with identical byte arrays may create strings that have different values on different systems. - -## Handle repetitive strings - -Apps that parse or decode streams of text often use the constructor or the method to convert sequences of characters into a string. Repeatedly creating new strings with the same value instead of creating and reusing one string wastes memory. If you are likely to create the same string value repeatedly by calling the constructor, even if you don't know in advance what those identical string values may be, you can use a lookup table instead. - -For example, suppose you read and parse a stream of characters from a file that contains XML tags and attributes. When you parse the stream, you repeatedly encounter certain tokens (that is, sequences of characters that have a symbolic meaning). Tokens equivalent to the strings "0", "1", "true", and "false" are likely to occur frequently in an XML stream. - -Instead of converting each token into a new string, you can create a object to hold commonly occurring strings. The object improves performance, because it retrieves stored strings without allocating temporary memory. When you encounter a token, use the method to retrieve the token from the table. If the token exists, the method returns the corresponding string. If the token does not exist, use the method to insert the token into the table and to get the corresponding string. - -## Example 1: Use string assignment - -The following example creates a new string by assigning it a string literal. It creates a second string by assigning the value of the first string to it. These are the two most common ways to instantiate a new object. - -:::code language="csharp" source="./snippets/System/String/.ctor/csharp/ctor1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/String/.ctor/fsharp/ctor1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/String/.ctor/vb/ctor1.vb" id="Snippet1"::: - -## Example 2: Use a character array - -The following example demonstrates how to create a new object from a character array. - -:::code language="csharp" source="./snippets/System/String/.ctor/csharp/source.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/String/.ctor/fsharp/source.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/String/.ctor/vb/source.vb" id="Snippet1"::: - -## Example 3: Use a portion of a character array and repeating a single character - -The following example demonstrates how to create a new object from a portion of a character array, and how to create a new object that contains multiple occurrences of a single character. - -:::code language="csharp" source="./snippets/System/String/.ctor/csharp/source.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/String/.ctor/fsharp/source.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/String/.ctor/vb/source.vb" id="Snippet3"::: - -## Example 4: Use a pointer to a character array - -The following example demonstrates how to create a new object from a pointer to an array of characters. The C# example must be compiled by using the `/unsafe` compiler switch. - -:::code language="csharp" source="./snippets/System/String/.ctor/csharp/ctor2.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/String/.ctor/fsharp/ctor2.fs" id="Snippet2"::: - -## Example 5: Instantiate a string from a pointer and a range of an array - -The following example examines the elements of a character array for either a period or an exclamation point. If one is found, it instantiates a string from the characters in the array that precede the punctuation symbol. If not, it instantiates a string with the entire contents of the array. The C# example must be compiled using the `/unsafe` compiler switch. - -:::code language="csharp" source="./snippets/System/String/.ctor/csharp/char2_ctor.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/String/.ctor/fsharp/char2_ctor.fs" id="Snippet3"::: - -## Example 6: Instantiate a string from a pointer to a signed byte array - -The following example demonstrates how you can create an instance of the class with the constructor. - -:::code language="csharp" source="./snippets/System/String/.ctor/csharp/source.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/String/.ctor/fsharp/source.fs" id="Snippet2"::: diff --git a/docs/fundamentals/runtime-libraries/system-string-format.md b/docs/fundamentals/runtime-libraries/system-string-format.md deleted file mode 100644 index 57d830f5e3a1d..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-string-format.md +++ /dev/null @@ -1,343 +0,0 @@ ---- -title: System.String.Format method -description: Learn about the System.String.Format method. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.String.Format method - -[!INCLUDE [context](includes/context.md)] - -[!INCLUDE[interpolated-strings](includes/interpolated-strings.md)] - -## Examples - -Numerous examples that call the method are interspersed throughout this article. You can also download a complete set of `String.Format` examples, which are included a [.NET Core project for C#](/samples/dotnet/samples/string-format/). - -The following are some of the examples included in the article: - -### Create a format string - -[Insert a string](#insert-a-string)\ -[The format item](#the-format-item)\ -[Format items that have the same index](#format-items-that-have-the-same-index) - -### Control formatted output - -[Control formatting](#control-formatting)\ -[Control spacing](#control-spacing)\ -[Control alignment](#control-alignment)\ -[Control the number of integral digits](#how-do-i-control-the-number-of-integral-digits)\ -[Control the number of digits after the decimal separator](#how-do-i-control-the-number-of-digits-after-the-decimal-separator)\ -[Include literal braces in the result string](#how-do-i-include-literal-braces--and--in-the-result-string) - -### Make format strings culture-sensitive - -[Make format strings culture-sensitive](#make-format-strings-culture-sensitive) - -### Customize the formatting operation - -[A custom formatting operation](#example-a-custom-formatting-operation)\ -[An intercept provider and Roman numeral formatter](#example-an-intercept-provider-and-roman-numeral-formatter) - -## Get started with the String.Format method - -Use if you need to insert the value of an object, variable, or expression into another string. For example, you can insert the value of a value into a string to display it to the user as a single string: - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/starting2.cs" id="Snippet35"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/starting2.fs" id="Snippet35"::: -:::code language="vb" source="./snippets/System/String/Format/vb/starting2.vb" id="Snippet35"::: - -And you can control that value's formatting: - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/starting2.cs" id="Snippet36"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/starting2.fs" id="Snippet36"::: -:::code language="vb" source="./snippets/System/String/Format/vb/starting2.vb" id="Snippet36"::: - -Besides formatting, you can also control alignment and spacing. - -### Insert a string - - starts with a format string, followed by one or more objects or expressions that will be converted to strings and inserted at a specified place in the format string. For example: - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/starting1.cs" id="Snippet30"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/starting1.fs" id="Snippet30"::: -:::code language="vb" source="./snippets/System/String/Format/vb/starting1.vb" id="Snippet30"::: - -The `{0}` in the format string is a format item. `0` is the index of the object whose string value will be inserted at that position. (Indexes start at 0.) If the object to be inserted is not a string, its `ToString` method is called to convert it to one before inserting it in the result string. - -Here's another example that uses two format items and two objects in the object list: - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/starting1.cs" id="Snippet31"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/starting1.fs" id="Snippet31"::: -:::code language="vb" source="./snippets/System/String/Format/vb/starting1.vb" id="Snippet31"::: - -You can have as many format items and as many objects in the object list as you want, as long as the index of every format item has a matching object in the object list. You also don't have to worry about which overload you call; the compiler will select the appropriate one for you. - -### Control formatting - -You can follow the index in a format item with a format string to control how an object is formatted. For example, `{0:d}` applies the "d" format string to the first object in the object list. Here is an example with a single object and two format items: - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/starting1.cs" id="Snippet32"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/starting1.fs" id="Snippet32"::: -:::code language="vb" source="./snippets/System/String/Format/vb/starting1.vb" id="Snippet32"::: - -Numerous types support format strings, including all numeric types (both [standard](../../standard/base-types/standard-numeric-format-strings.md) and [custom](../../standard/base-types/custom-numeric-format-strings.md) format strings), all dates and times (both [standard](../../standard/base-types/standard-date-and-time-format-strings.md) and [custom](../../standard/base-types/custom-date-and-time-format-strings.md) format strings) and time intervals (both [standard](../../standard/base-types/standard-timespan-format-strings.md) and [custom](../../standard/base-types/custom-timespan-format-strings.md) format strings), all enumeration types [enumeration types](../../standard/base-types/enumeration-format-strings.md), and [GUIDs](xref:System.Guid.ToString(System.String)). You can also add support for format strings to your own types. - -### Control spacing - -You can define the width of the string that's inserted into the result string by using syntax such as `{0,12}`, which inserts a 12-character string. In this case, the string representation of the first object is right-aligned in the 12-character field. (If the string representation of the first object is more than 12 characters in length, though, the preferred field width is ignored, and the entire string is inserted into the result string.) - -The following example defines a 6-character field to hold the string "Year" and some year strings, as well as an 15-character field to hold the string "Population" and some population data. Note that the characters are right-aligned in the field. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/starting3.cs" id="Snippet33"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/starting3.fs" id="Snippet33"::: -:::code language="vb" source="./snippets/System/String/Format/vb/starting1.vb" id="Snippet33"::: - -### Control alignment - -By default, strings are right-aligned within their field if you specify a field width. To left-align strings in a field, you preface the field width with a negative sign, such as `{0,-12}` to define a 12-character left-aligned field. - -The following example is similar to the previous one, except that it left-aligns both labels and data. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/starting1.cs" id="Snippet34"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/starting1.fs" id="Snippet34"::: -:::code language="vb" source="./snippets/System/String/Format/vb/starting1.vb" id="Snippet34"::: - - makes use of the composite formatting feature. For more information, see [Composite Formatting](../../standard/base-types/composite-formatting.md). - -## Which method do I call? - -| Objective | Method to call | -|-----------|----------------| -|Format one or more objects by using the conventions of the current culture.|Except for the overloads that include a `provider` parameter, the remaining overloads include a parameter followed by one or more object parameters. Because of this, you don't have to determine which overload you intend to call. Your language compiler selects the appropriate overload from among the overloads that don't have a `provider` parameter, based on your argument list. For example, if your argument list has five arguments, the compiler calls the method.| -|Format one or more objects by using the conventions of a specific culture.|Each overload that begins with a `provider` parameter is followed by a parameter and one or more object parameters. Because of this, you don't have to determine which specific overload you intend to call. Your language compiler selects the appropriate overload from among the overloads that have a `provider` parameter, based on your argument list. For example, if your argument list has five arguments, the compiler calls the method.| -|Perform a custom formatting operation either with an implementation or an implementation.|Any of the four overloads with a `provider` parameter. The compiler selects the appropriate overload from among the overloads that have a `provider` parameter, based on your argument list.| - -## The Format method in brief - -Each overload of the method uses the [composite formatting feature](../../standard/base-types/composite-formatting.md) to include zero-based indexed placeholders, called *format items*, in a composite format string. At runtime, each format item is replaced with the string representation of the corresponding argument in a parameter list. If the value of the argument is `null`, the format item is replaced with . For example, the following call to the method includes a format string with three format items, {0}, {1}, and {2}, and an argument list with three items. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/formatoverload1.cs" id="Snippet8"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/formatoverload1.fs" id="Snippet8"::: -:::code language="vb" source="./snippets/System/String/Format/vb/formatoverload1.vb" id="Snippet8"::: - -## The format item - -A format item has this syntax: - -```txt -{index[,width][:formatString]} -``` - -Brackets denote optional elements. The opening and closing braces are required. (To include a literal opening or closing brace in the format string, see the [Escaping Braces](../../standard/base-types/composite-formatting.md#escaping-braces) section in the [Composite Formatting](../../standard/base-types/composite-formatting.md) article.) - -For example, a format item to format a currency value might appear like this: - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/formatsyntax1.cs" id="Snippet12"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/formatsyntax1.fs" id="Snippet12"::: -:::code language="vb" source="./snippets/System/String/Format/vb/formatsyntax1.vb" id="Snippet12"::: - -A format item has the following elements: - -`index`\ -The zero-based index of the argument whose string representation is to be included at this position in the string. If this argument is `null`, an empty string will be included at this position in the string. - -`width`\ -Optional. A signed integer that indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer). If you omit `width`, the string representation of the corresponding argument is inserted in a field with no leading or trailing spaces. - -If the value of `width` is less than the length of the argument to be inserted, `width` is ignored and the length of the string representation of the argument is used as the field width. - -`formatString`\ -Optional. A string that specifies the format of the corresponding argument's result string. If you omit `formatString`, the corresponding argument's parameterless `ToString` method is called to produce its string representation. If you specify `formatString`, the argument referenced by the format item must implement the interface. Types that support format strings include: - -- All integral and floating-point types. (See [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md).) - -- and . (See [Standard Date and Time Format Strings](../../standard/base-types/standard-date-and-time-format-strings.md) and [Custom Date and Time Format Strings](../../standard/base-types/custom-date-and-time-format-strings.md).) - -- All enumeration types. (See [Enumeration Format Strings](../../standard/base-types/enumeration-format-strings.md).) - -- values. (See [Standard TimeSpan Format Strings](../../standard/base-types/standard-timespan-format-strings.md) and [Custom TimeSpan Format Strings](../../standard/base-types/custom-timespan-format-strings.md).) - -- GUIDs. (See the method.) - -However, any custom type can implement or extend an existing type's implementation. - -The following example uses the `width` and `formatString` arguments to produce formatted output. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/formatoverload2.cs" id="Snippet9"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/formatoverload2.fs" id="Snippet9"::: -:::code language="vb" source="./snippets/System/String/Format/vb/formatoverload2.vb" id="Snippet9"::: - -## How arguments are formatted - -Format items are processed sequentially from the beginning of the string. Each format item has an index that corresponds to an object in the method's argument list. The method retrieves the argument and derives its string representation as follows: - -- If the argument is `null`, the method inserts into the result string. You don't have to be concerned with handling a for null arguments. - -- If you call the overload and the `provider` object's implementation returns a non-null implementation, the argument is passed to its method. If the format item includes a `formatString` argument, it is passed as the first argument to the method. If the implementation is available and produces a non-null string, that string is returned as the string representation of the argument; otherwise, the next step executes. - -- If the argument implements the interface, its implementation is called. - -- The argument's parameterless `ToString` method, which either overrides or inherits from a base class implementation, is called. - -For an example that intercepts calls to the method and allows you to see what information the method passes to a formatting method for each format item in a composite format string, see [Example: An intercept provider and Roman numeral formatter](#example-an-intercept-provider-and-roman-numeral-formatter). - -For more information, see [Processing order](../../standard/base-types/composite-formatting.md#processing-order). - -## Format items that have the same index - -The method throws a exception if the index of an index item is greater than or equal to the number of arguments in the argument list. However, `format` can include more format items than there are arguments, as long as multiple format items have the same index. In the call to the method in following example, the argument list has a single argument, but the format string includes two format items: one displays the decimal value of a number, and the other displays its hexadecimal value. - -:::code language="csharp" source="./snippets/System/String/Format/csharp/Example1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/String/Format/fsharp/Example1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/String/Format/vb/Example1.vb" id="Snippet1"::: - -## Format and culture - -Generally, objects in the argument list are converted to their string representations by using the conventions of the current culture, which is returned by the property. You can control this behavior by calling one of the overloads of that includes a `provider` parameter. The `provider` parameter is an implementation that supplies custom and culture-specific formatting information that is used to moderate the formatting process. - -The interface has a single member, , which is responsible for returning the object that provides formatting information. .NET has three implementations that provide culture-specific formatting: - -- . Its method returns a culture-specific object for formatting numeric values and a culture-specific object for formatting date and time values. -- , which is used for culture-specific formatting of date and time values. Its method returns itself. -- , which is used for culture-specific formatting of numeric values. Its method returns itself. - -## Custom formatting operations - -You can also call the any of the overloads of the method that have a `provider` parameter of type to perform custom formatting operations. For example, you could format an integer as an identification number or as a telephone number. To perform custom formatting, your `provider` argument must implement both the and interfaces. When the method is passed an implementation as the `provider` argument, the method calls its implementation and requests an object of type . It then calls the returned object's method to format each format item in the composite string passed to it. - -For more information about providing custom formatting solutions, see [How to: Define and Use Custom Numeric Format Providers](../../standard/base-types/how-to-define-and-use-custom-numeric-format-providers.md) and . For an example that converts integers to formatted custom numbers, see [Example: A custom formatting operation](#example-a-custom-formatting-operation). For an example that converts unsigned bytes to Roman numerals, see [Example: An intercept provider and Roman numeral formatter](#example-an-intercept-provider-and-roman-numeral-formatter). - -### Example: A custom formatting operation - -This example defines a format provider that formats an integer value as a customer account number in the form x-xxxxx-xx. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/FormatExample2.cs" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/FormatExample2.fs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/String/Format/vb/FormatExample2.vb" id="Snippet2"::: - -### Example: An intercept provider and Roman numeral formatter - -This example defines a custom format provider that implements the and interfaces to do two things: - -- It displays the parameters passed to its implementation. This enables us to see what parameters the method is passing to the custom formatting implementation for each object that it tries to format. This can be useful when you're debugging your application. -- If the object to be formatted is an unsigned byte value that is to be formatted by using the "R" standard format string, the custom formatter formats the numeric value as a Roman numeral. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/interceptor2.cs" id="Snippet11"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/interceptor2.fs" id="Snippet11"::: -:::code language="vb" source="./snippets/System/String/Format/vb/interceptor2.vb" id="Snippet11"::: - -## FAQ - -### Why do you recommend string interpolation over calls to the `String.Format` method? - -String interpolation is: - -- More flexible. It can be used in any string without requiring a call to a method that supports composite formatting. Otherwise, you have to call the method or another method that supports composite formatting, such as or . -- More readable. Because the expression to insert into a string appears in the interpolated expression rather than in a argument list, interpolated strings are easier to code and to read. Interpolated strings can also be used in string concatenation operations to produce more concise, clearer code. - -A comparison of the following two code examples illustrates the superiority of interpolated strings over string concatenation and calls to composite formatting methods. The use of multiple string concatenation operations in the following example produces verbose and hard-to-read code. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa-interpolated1.cs" id="SnippetQAInterpolated"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa-interpolated1.fs" id="SnippetQAInterpolated"::: -:::code language="vb" source="./snippets/System/String/Format/vb/qa-interpolated1.vb"::: - -In contrast, the use of interpolated strings in the following example produces much clearer, more concise code than the string concatenation statement and the call to the method in the previous example. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa-interpolated2.cs" id="SnippetQAInterpolated2"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa-interpolated2.fs" id="SnippetQAInterpolated2"::: -:::code language="vb" source="./snippets/System/String/Format/vb/qa-interpolated2.vb"::: - -### Where can I find the predefined format strings? - -- For all integral and floating-point types, see [Standard Numeric Format Strings](../../standard/base-types/standard-numeric-format-strings.md) and [Custom Numeric Format Strings](../../standard/base-types/custom-numeric-format-strings.md). -- For date and time values, see [Standard Date and Time Format Strings](../../standard/base-types/standard-date-and-time-format-strings.md) and [Custom Date and Time Format Strings](../../standard/base-types/custom-date-and-time-format-strings.md). -- For enumeration values, see [Enumeration Format Strings](../../standard/base-types/enumeration-format-strings.md). -- For values, see [Standard TimeSpan Format Strings](../../standard/base-types/standard-timespan-format-strings.md) and [Custom TimeSpan Format Strings](../../standard/base-types/custom-timespan-format-strings.md). -- For values, see the Remarks section of the reference page. - -### How do I control the alignment of the result strings that replace format items? - -The general syntax of a format item is: - -```txt -{index[,width][: formatString]} -``` - -`width` is a signed integer that defines the field width. If this value is negative, text in the field is left-aligned. If it is positive, text is right-aligned. - -### How do I control the number of digits after the decimal separator? - -All [standard numeric format strings](../../standard/base-types/standard-numeric-format-strings.md) except "D" (which is used with integers only), "G", "R", and "X" allow a precision specifier that defines the number of decimal digits in the result string. The following example uses standard numeric format strings to control the number of decimal digits in the result string. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa26.cs" id="Snippet26"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa26.fs" id="Snippet26"::: -:::code language="vb" source="./snippets/System/String/Format/vb/qa26.vb" id="Snippet26"::: - -If you're using a [custom numeric format string](../../standard/base-types/custom-numeric-format-strings.md), use the "0" format specifier to control the number of decimal digits in the result string, as the following example shows. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa27.cs" id="Snippet27"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa27.fs" id="Snippet27"::: -:::code language="vb" source="./snippets/System/String/Format/vb/qa27.vb" id="Snippet27"::: - -### How do I control the number of integral digits? - -By default, formatting operations only display non-zero integral digits. If you're formatting integers, you can use a precision specifier with the "D" and "X" standard format strings to control the number of digits. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa29.cs" id="Snippet29"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa29.fs" id="Snippet29"::: -:::code language="vb" source="./snippets/System/String/Format/vb/qa29.vb" id="Snippet29"::: - -You can pad an integer or floating-point number with leading zeros to produce a result string with a specified number of integral digits by using the "0" [custom numeric format specifier](../../standard/base-types/custom-numeric-format-strings.md), as the following example shows. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa28.cs" id="Snippet28"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa28.fs" id="Snippet28"::: -:::code language="vb" source="./snippets/System/String/Format/vb/qa28.vb" id="Snippet28"::: - -### How many items can I include in the format list? - -There is no practical limit. The second parameter of the method is tagged with the attribute, which allows you to include either a delimited list or an object array as your format list. - -### How do I include literal braces ("{" and "}") in the result string? - -For example, how do you prevent the following method call from throwing a exception? - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa3.cs" id="Snippet23"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa3.fs" id="Snippet23"::: -:::code language="vb" source="./snippets/System/String/Format/vb/qa3.vb" id="Snippet23"::: - -A single opening or closing brace is always interpreted as the beginning or end of a format item. To be interpreted literally, it must be escaped. You escape a brace by adding another brace ("{{" and "}}" instead of "{" and "}"), as in the following method call: - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa3.cs" id="Snippet24"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa3.fs" id="Snippet24"::: -:::code language="vb" source="./snippets/System/String/Format/vb/qa3.vb" id="Snippet24"::: - -However, even escaped braces are easily misinterpreted. We recommend that you include braces in the format list and use format items to insert them in the result string, as the following example shows. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa3.cs" id="Snippet25"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa3.fs" id="Snippet25"::: -:::code language="vb" source="./snippets/System/String/Format/vb/qa3.vb" id="Snippet25"::: - -### Why does my call to the String.Format method throw a FormatException? - -The most common cause of the exception is that the index of a format item doesn't correspond to an object in the format list. Usually this indicates that you've misnumbered the indexes of format items or you've forgotten to include an object in the format list. Attempting to include an unescaped left or right brace character also throws a . Occasionally, the exception is the result of a typo; for example, a typical mistake is to mistype "[" (the left bracket) instead of "{" (the left brace). - -### If the Format(System.IFormatProvider,System.String,System.Object[]) method supports parameter arrays, why does my code throw an exception when I use an array? - -For example, the following code throws a exception: - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa11.cs" id="Snippet21"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa11.fs" id="Snippet21"::: -:::code language="vb" source="./snippets/System/String/Format/vb/qa1.vb" id="Snippet21"::: - -This is a problem of compiler overload resolution. Because the compiler cannot convert an array of integers to an object array, it treats the integer array as a single argument, so it calls the method. The exception is thrown because there are four format items but only a single item in the format list. - -Because neither Visual Basic nor C# can convert an integer array to an object array, you have to perform the conversion yourself before calling the method. The following example provides one implementation. - -:::code language="csharp" source="./snippets/System/FormatException/Overview/csharp/qa21.cs" id="Snippet22"::: -:::code language="fsharp" source="./snippets/System/FormatException/Overview/fsharp/qa21.fs" id="Snippet22"::: -:::code language="vb" source="./snippets/System/String/Format/vb/qa2.vb" id="Snippet22"::: diff --git a/docs/fundamentals/runtime-libraries/system-string-intern.md b/docs/fundamentals/runtime-libraries/system-string-intern.md deleted file mode 100644 index cf077060d9153..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-string-intern.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: System.String.Intern method -description: Learn about the System.String.Intern method. -ms.date: 03/27/2026 -ai-usage: ai-assisted -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.String.Intern method - -[!INCLUDE [context](includes/context.md)] - -The common language runtime maintains a table, called the *intern pool*, that holds a single reference for each unique string value. The method uses the intern pool to search for a string equal to the value of `str`. If no such string exists, a reference to `str` is added to the pool, and that reference is returned. (In contrast, the method returns a null reference if the requested string doesn't exist in the intern pool.) - -The intern pool can be used by the runtime to conserve string storage. However, automatic interning of string literals isn't guaranteed—depending on how the assembly was compiled and executed, some literals might not be added to the pool. - -In the following example, the string `s1` has a value of "MyTest". The class generates a new string object that has the same value as `s1`. A reference to that string is assigned to `s2`. The method searches for a string that has the same value as `s2`. If `s1` was already interned (for example, because the assembly requires string-literal interning), the method returns the same reference as `s1`, which is then assigned to `s3`, and `s1` and `s3` compare equal. Otherwise, a new interned entry is created for `s2` and assigned to `s3`, and `s1` and `s3` compare unequal. In either case, `s1` and `s2` compare unequal because they refer to different objects. - -:::code language="csharp" source="./snippets/System/String/Intern/csharp/Intern1.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/String/Intern/fsharp/Intern1.fs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/String/Intern/vb/Intern1.vb" id="Snippet1"::: - -## Performance considerations - -If you're trying to reduce the total amount of memory your application allocates, keep in mind that interning a string has two unwanted side effects. First, the memory allocated for interned objects is not likely to be released until the common language runtime (CLR) terminates. The reason is that the CLR's reference to the interned object can persist after your application, or even your application domain, terminates. Second, to intern a string, you must first create the string. The memory used by the object must still be allocated, even though the memory will eventually be garbage collected. - -The enumeration member marks an assembly as not requiring string-literal interning. By default, the C# compiler emits a with the flag on each assembly for better performance, which means string literals are not guaranteed to be added to the intern pool. You can customize on an assembly using the attribute. - -When you publish an app using [native AOT](../../core/deploying/native-aot/index.md), turning off is not supported. With native AOT, string literals aren't guaranteed to be added to the intern pool, so might not find a match for a string that appears to be a literal in source code. diff --git a/docs/fundamentals/runtime-libraries/system-string-isnullorempty.md b/docs/fundamentals/runtime-libraries/system-string-isnullorempty.md deleted file mode 100644 index 499aba7be8105..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-string-isnullorempty.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: System.String.IsNullOrEmpty method -description: Learn about the System.String.IsNullOrEmpty method. -ms.date: 01/24/2024 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.String.IsNullOrEmpty method - -[!INCLUDE [context](includes/context.md)] - - is a convenience method that enables you to simultaneously test whether a is `null` or its value is . It is equivalent to the following code: - -:::code language="csharp" source="./snippets/System/String/IsNullOrEmpty/csharp/isnullorempty1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System/String/IsNullOrEmpty/vb/isnullorempty1.vb" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System/String/IsNullOrEmpty/fsharp/isnullorempty1.fs" id="Snippet1"::: - -You can use the method to test whether a string is `null`, its value is , or it consists only of white-space characters. - -## What is a null string? - -A string is `null` if it has not been assigned a value (in C++ and Visual Basic) or if it has explicitly been assigned a value of `null`. Although the [composite formatting](../../standard/base-types/composite-formatting.md) feature can gracefully handle a null string, as the following example shows, attempting to call one if its members throws a . - -:::code language="csharp" source="./snippets/System/String/IsNullOrEmpty/csharp/NullString1.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System/String/IsNullOrEmpty/vb/NullString1.vb" id="Snippet2"::: -:::code language="fsharp" source="./snippets/System/String/IsNullOrEmpty/fsharp/NullString1.fs" id="Snippet2"::: - -## What is an empty string? - -A string is empty if it's explicitly assigned an empty string ("") or . An empty string has a of 0. The following example creates an empty string and displays its value and its length. - -:::code language="csharp" source="./snippets/System/String/IsNullOrEmpty/csharp/NullString1.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/String/IsNullOrEmpty/vb/NullString1.vb" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/String/IsNullOrEmpty/fsharp/NullString2.fs" id="Snippet3"::: diff --git a/docs/fundamentals/runtime-libraries/system-string.md b/docs/fundamentals/runtime-libraries/system-string.md deleted file mode 100644 index c8ec4dc5e8e77..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-string.md +++ /dev/null @@ -1,459 +0,0 @@ ---- -title: System.String class -description: Learn about the System.String class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.String class - -[!INCLUDE [context](includes/context.md)] - -A string is a sequential collection of characters that's used to represent text. A object is a sequential collection of objects that represent a string; a object corresponds to a UTF-16 code unit. The value of the object is the content of the sequential collection of objects, and that value is immutable (that is, it is read-only). For more information about the immutability of strings, see the [Immutability and the StringBuilder class](#immutability-and-the-stringbuilder-class) section. The maximum size of a object in memory is 2-GB, or about 1 billion characters. - -For more information about Unicode, UTF-16, code units, code points, and the and types, see [Introduction to character encoding in .NET](../../standard/base-types/character-encoding-introduction.md). - -## Instantiate a String object - -You can instantiate a object in the following ways: - -- By assigning a string literal to a variable. This is the most commonly used method for creating a string. The following example uses assignment to create several strings. Note that in C# and F#, because the backslash (\\) is an escape character, literal backslashes in a string must be escaped or the entire string must be @-quoted. - - :::code language="csharp" source="./snippets/System/String/Overview/csharp/program.cs" id="Snippet1"::: - :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/program.fs" id="Snippet1"::: - :::code language="vb" source="./snippets/System/String/Overview/vb/instantiate1.vb" id="Snippet1"::: - -- By calling a class constructor. The following example instantiates strings by calling several class constructors. Note that some of the constructors include pointers to character arrays or signed byte arrays as parameters. Visual Basic does not support calls to these constructors. For detailed information about constructors, see the constructor summary. - - :::code language="csharp" source="./snippets/System/String/Overview/csharp/program.cs" id="Snippet2"::: - :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/program.fs" id="Snippet2"::: - :::code language="vb" source="./snippets/System/String/Overview/vb/instantiate1.vb" id="Snippet2"::: - -- By using the string concatenation operator (+ in C# and F#, and & or + in Visual Basic) to create a single string from any combination of instances and string literals. The following example illustrates the use of the string concatenation operator. - - :::code language="csharp" source="./snippets/System/String/Overview/csharp/program.cs" id="Snippet3"::: - :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/program.fs" id="Snippet3"::: - :::code language="vb" source="./snippets/System/String/Overview/vb/instantiate1.vb" id="Snippet3"::: - -- By retrieving a property or calling a method that returns a string. The following example uses the methods of the class to extract a substring from a larger string. - - :::code language="csharp" source="./snippets/System/String/Overview/csharp/program.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/program.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System/String/Overview/vb/instantiate1.vb" id="Snippet4"::: - -- By calling a formatting method to convert a value or object to its string representation. The following example uses the [composite formatting](../../standard/base-types/composite-formatting.md) feature to embed the string representation of two objects into a string. - - :::code language="csharp" source="./snippets/System/String/Overview/csharp/program.cs" id="Snippet5"::: - :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/program.fs" id="Snippet5"::: - :::code language="vb" source="./snippets/System/String/Overview/vb/instantiate1.vb" id="Snippet5"::: - -## Char objects and Unicode characters - -Each character in a string is defined by a Unicode scalar value, also called a Unicode code point or the ordinal (numeric) value of the Unicode character. Each code point is encoded by using UTF-16 encoding, and the numeric value of each element of the encoding is represented by a object. - -> [!NOTE] -> Note that, because a instance consists of a sequential collection of UTF-16 code units, it is possible to create a object that is not a well-formed Unicode string. For example, it is possible to create a string that has a low surrogate without a corresponding high surrogate. Although some methods, such as the methods of encoding and decoding objects in the namespace, may performs checks to ensure that strings are well-formed, class members don't ensure that a string is well-formed. - -A single object usually represents a single code point; that is, the numeric value of the equals the code point. For example, the code point for the character "a" is U+0061. However, a code point might require more than one encoded element (more than one object). The Unicode standard defines two types of characters that correspond to multiple objects: graphemes, and Unicode supplementary code points that correspond to characters in the Unicode supplementary planes. - -- A grapheme is represented by a base character followed by one or more combining characters. For example, the character ä is represented by a object whose code point is U+0061 followed by a object whose code point is U+0308. This character can also be defined by a single object that has a code point of U+00E4. As the following example shows, a culture-sensitive comparison for equality indicates that these two representations are equal, although an ordinary ordinal comparison does not. However, if the two strings are normalized, an ordinal comparison also indicates that they are equal. (For more information on normalizing strings, see the [Normalization](#normalization) section.) - - :::code language="csharp" source="./snippets/System/String/Overview/csharp/grapheme1.cs" id="Snippet2"::: - :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/grapheme1.fs" id="Snippet2"::: - :::code language="vb" source="./snippets/System/String/Overview/vb/grapheme1.vb" id="Snippet2"::: - -- A Unicode supplementary code point (a surrogate pair) is represented by a object whose code point is a high surrogate followed by a object whose code point is a low surrogate. The code units of high surrogates range from U+D800 to U+DBFF. The code units of low surrogates range from U+DC00 to U+DFFF. Surrogate pairs are used to represent characters in the 16 Unicode supplementary planes. The following example creates a surrogate character and passes it to the method to determine whether it is a surrogate pair. - - :::code language="csharp" source="./snippets/System/String/Overview/csharp/surrogate1.cs" id="Snippet3"::: - :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/surrogate1.fs" id="Snippet3"::: - :::code language="vb" source="./snippets/System/String/Overview/vb/surrogate1.vb" id="Snippet3"::: - -## The Unicode standard - -Characters in a string are represented by UTF-16 encoded code units, which correspond to values. - -Each character in a string has an associated Unicode character category, which is represented in .NET by the enumeration. The category of a character or a surrogate pair can be determined by calling the method. - -[!INCLUDE[character-categories](./includes/unicode-categories.md)] - -In addition, .NET supports string comparison and sorting based on the Unicode standard. Starting with .NET Framework 4.5 running on Windows 8 and later versions of the Windows operating system, the runtime delegates string comparison and sorting operations to the operating system. On .NET Core and .NET 5+, string comparison and sorting information is provided by [International Components for Unicode](https://icu.unicode.org/) libraries (except on Windows versions prior to Windows 10 May 2019 Update). The following table lists the versions of .NET and the versions of the Unicode Standard on which character comparison and sorting are based. - -|.NET version|Version of the Unicode Standard| -|----------------------------|-------------------------------------| -|.NET Framework 4.5 and later on Windows 7|[The Unicode Standard, Version 5.0.0](https://www.unicode.org/versions/Unicode5.0.0)| -|.NET Framework 4.5 and later on Windows 8 and later Windows operating systems|[The Unicode Standard, Version 6.3.0](https://www.unicode.org/versions/Unicode6.3.0/)| -|.NET Core and .NET 5+|Depends on the version of the Unicode Standard supported by the underlying operating system.| - -## Embedded null characters - -In .NET, a object can include embedded null characters, which count as a part of the string's length. However, in some languages such as C and C++, a null character indicates the end of a string; it is not considered a part of the string and is not counted as part of the string's length. This means that the following common assumptions that C and C++ programmers or libraries written in C or C++ might make about strings are not necessarily valid when applied to objects: - -- The value returned by the `strlen` or `wcslen` functions does not necessarily equal . - -- The string created by the `strcpy_s` or `wcscpy_s` functions is not necessarily identical to the string being copied. - -You should ensure that native C and C++ code that instantiates objects, and code that is passed objects through platform invoke, don't assume that an embedded null character marks the end of the string. - -Embedded null characters in a string are also treated differently when a string is sorted (or compared) and when a string is searched. Null characters are ignored when performing culture-sensitive comparisons between two strings, including comparisons using the invariant culture. They are considered only for ordinal or case-insensitive ordinal comparisons. On the other hand, embedded null characters are always considered when searching a string with methods such as , , and . - -## Strings and indexes - -An index is the position of a object (not a Unicode character) in a . An index is a zero-based, nonnegative number that starts from the first position in the string, which is index position zero. A number of search methods, such as and , return the index of a character or substring in the string instance. - -The property lets you access individual objects by their index position in the string. Because the property is the default property (in Visual Basic) or the indexer (in C# and F#), you can access the individual objects in a string by using code such as the following. This code looks for white space or punctuation characters in a string to determine how many words the string contains. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/index11.cs" id="Snippet4"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/index11.fs" id="Snippet4"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/index1.vb" id="Snippet4"::: - -Because the class implements the interface, you can also iterate through the objects in a string by using a `foreach` construct, as the following example shows. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/index2.cs" id="Snippet5"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/index2.fs" id="Snippet5"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/index2.vb" id="Snippet5"::: - -Consecutive index values might not correspond to consecutive Unicode characters, because a Unicode character might be encoded as more than one object. In particular, a string may contain multi-character units of text that are formed by a base character followed by one or more combining characters or by surrogate pairs. To work with Unicode characters instead of objects, use the and classes, or the method and the struct. The following example illustrates the difference between code that works with objects and code that works with Unicode characters. It compares the number of characters or text elements in each word of a sentence. The string includes two sequences of a base character followed by a combining character. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/index3.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/index3.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/index3.vb" id="Snippet6"::: - -This example works with text elements by using the method and the class to enumerate all the text elements in a string. You can also retrieve an array that contains the starting index of each text element by calling the method. - -For more information about working with units of text rather than individual values, see [Introduction to character encoding in .NET](../../standard/base-types/character-encoding-introduction.md). - -## Null strings and empty strings - -A string that has been declared but has not been assigned a value is `null`. Attempting to call methods on that string throws a . A null string is different from an empty string, which is a string whose value is "" or . In some cases, passing either a null string or an empty string as an argument in a method call throws an exception. For example, passing a null string to the method throws an , and passing an empty string throws a . In other cases, a method argument can be either a null string or an empty string. For example, if you are providing an implementation for a class, you want to equate both a null string and an empty string with the general ("G") format specifier. - -The class includes the following two convenience methods that enable you to test whether a string is `null` or empty: - -- , which indicates whether a string is either `null` or is equal to . This method eliminates the need to use code such as the following: - - :::code language="csharp" source="./snippets/System/String/Overview/csharp/nullorempty1.cs" id="Snippet1"::: - :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/nullorempty1.fs" id="Snippet1"::: - :::code language="vb" source="./snippets/System/String/Overview/vb/nullorempty1.vb" id="Snippet1"::: - -- , which indicates whether a string is `null`, equals , or consists exclusively of white-space characters. This method eliminates the need to use code such as the following: - - :::code language="csharp" source="./snippets/System/String/Overview/csharp/nullorempty1.cs" id="Snippet2"::: - :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/nullorempty1.fs" id="Snippet2"::: - :::code language="vb" source="./snippets/System/String/Overview/vb/nullorempty1.vb" id="Snippet2"::: - -The following example uses the method in the implementation of a custom `Temperature` class. The method supports the "G", "C", "F", and "K" format strings. If an empty format string or a format string whose value is `null` is passed to the method, its value is changed to the "G" format string. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/nullorempty1.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/nullorempty1.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/nullorempty1.vb" id="Snippet3"::: - -## Immutability and the StringBuilder class - -A object is called immutable (read-only), because its value cannot be modified after it has been created. Methods that appear to modify a object actually return a new object that contains the modification. - -Because strings are immutable, string manipulation routines that perform repeated additions or deletions to what appears to be a single string can exact a significant performance penalty. For example, the following code uses a random number generator to create a string with 1000 characters in the range 0x0001 to 0x052F. Although the code appears to use string concatenation to append a new character to the existing string named `str`, it actually creates a new object for each concatenation operation. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/immutable.cs" id="Snippet15"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/immutable.fs" id="Snippet15"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/immutable.vb" id="Snippet15"::: - -You can use the class instead of the class for operations that make multiple changes to the value of a string. Unlike instances of the class, objects are mutable; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string. When you have finished modifying the value of a object, you can call its method to convert it to a string. The following example replaces the used in the previous example to concatenate 1000 random characters in the range to 0x0001 to 0x052F with a object. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/immutable1.cs" id="Snippet16"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/immutable1.fs" id="Snippet16"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/immutable1.vb" id="Snippet16"::: - -## Ordinal vs. culture-sensitive operations - -Members of the class perform either ordinal or culture-sensitive (linguistic) operations on a object. An ordinal operation acts on the numeric value of each object. A culture-sensitive operation acts on the value of the object, and takes culture-specific casing, sorting, formatting, and parsing rules into account. Culture-sensitive operations execute in the context of an explicitly declared culture or the implicit current culture. The two kinds of operations can produce very different results when they are performed on the same string. - -.NET also supports culture-insensitive linguistic string operations by using the invariant culture (), which is loosely based on the culture settings of the English language independent of region. Unlike other settings, the settings of the invariant culture are guaranteed to remain consistent on a single computer, from system to system, and across versions of .NET. The invariant culture can be seen as a kind of black box that ensures stability of string comparisons and ordering across all cultures. - -> [!IMPORTANT] -> If your application makes a security decision about a symbolic identifier such as a file name or named pipe, or about persisted data such as the text-based data in an XML file, the operation should use an ordinal comparison instead of a culture-sensitive comparison. This is because a culture-sensitive comparison can yield different results depending on the culture in effect, whereas an ordinal comparison depends solely on the binary value of the compared characters. - -> [!IMPORTANT] -> Most methods that perform string operations include an overload that has a parameter of type , which enables you to specify whether the method performs an ordinal or culture-sensitive operation. In general, you should call this overload to make the intent of your method call clear. For best practices and guidance for using ordinal and culture-sensitive operations on strings, see [Best Practices for Using Strings](../../standard/base-types/best-practices-strings.md). - -Operations for casing, parsing and formatting, comparison and sorting, and testing for equality can be either ordinal or culture-sensitive. The following sections discuss each category of operation. - -> [!TIP] -> You should always call a method overload that makes the intent of your method call clear. For example, instead of calling the method to perform a culture-sensitive comparison of two strings by using the conventions of the current culture, you should call the method with a value of for the `comparisonType` argument. For more information, see [Best Practices for Using Strings](../../standard/base-types/best-practices-strings.md). - -You can download the sorting weight tables, a set of text files that contain information on the character weights used in sorting and comparison operations, from the following links: - -- Windows (.NET Framework and .NET Core): [Sorting Weight Tables](https://www.microsoft.com/download/details.aspx?id=10921) -- Windows 10 May 2019 Update or later (.NET 5+) and Linux and macOS (.NET Core and .NET 5+): [Default Unicode Collation Element Table](https://www.unicode.org/Public/UCA/latest/allkeys.txt) - -### Casing - -Casing rules determine how to change the capitalization of a Unicode character; for example, from lowercase to uppercase. Often, a casing operation is performed before a string comparison. For example, a string might be converted to uppercase so that it can be compared with another uppercase string. You can convert the characters in a string to lowercase by calling the or method, and you can convert them to uppercase by calling the or method. In addition, you can use the method to convert a string to title case. - -[!INCLUDE[platform-note](./includes/c-and-posix-cultures.md)] - -Casing operations can be based on the rules of the current culture, a specified culture, or the invariant culture. Because case mappings can vary depending on the culture used, the result of casing operations can vary based on culture. The actual differences in casing are of three kinds: - -- Differences in the case mapping of LATIN CAPITAL LETTER I (U+0049), LATIN SMALL LETTER I (U+0069), LATIN CAPITAL LETTER I WITH DOT ABOVE (U+0130), and LATIN SMALL LETTER DOTLESS I (U+0131). In the tr-TR (Turkish (Turkey)) and az-Latn-AZ (Azerbaijan, Latin) cultures, and in the tr, az, and az-Latn neutral cultures, the lowercase equivalent of LATIN CAPITAL LETTER I is LATIN SMALL LETTER DOTLESS I, and the uppercase equivalent of LATIN SMALL LETTER I is LATIN CAPITAL LETTER I WITH DOT ABOVE. In all other cultures, including the invariant culture, LATIN SMALL LETTER I and LATIN CAPITAL LETTER I are lowercase and uppercase equivalents. - - The following example demonstrates how a string comparison designed to prevent file system access can fail if it relies on a culture-sensitive casing comparison. (The casing conventions of the invariant culture should have been used.) - - :::code language="csharp" source="./snippets/System/String/Overview/csharp/case2.cs" id="Snippet17"::: - :::code language="fsharp" source="./snippets/System/String/Overview/fsharp/case2.fs" id="Snippet17"::: - :::code language="vb" source="./snippets/System/String/Overview/vb/case2.vb" id="Snippet17"::: - -- Differences in case mappings between the invariant culture and all other cultures. In these cases, using the casing rules of the invariant culture to change a character to uppercase or lowercase returns the same character. For all other cultures, it returns a different character. Some of the affected characters are listed in the following table. - - |Character|If changed to|Returns| - |---------------|-------------------|-------------| - |MICRON SIGN (U+00B5)|Uppercase|GREEK CAPITAL LETTER MU (U+-39C)| - |LATIN CAPITAL LETTER I WITH DOT ABOVE (U+0130)|Lowercase|LATIN SMALL LETTER I (U+0069)| - |LATIN SMALL LETTER DOTLESS I (U+0131)|Uppercase|LATIN CAPITAL LETTER I (U+0049)| - |LATIN SMALL LETTER LONG S (U+017F)|Uppercase|LATIN CAPITAL LETTER S (U+0053)| - |LATIN CAPITAL LETTER D WITH SMALL LETTER Z WITH CARON (U+01C5)|Lowercase|LATIN SMALL LETTER DZ WITH CARON (U+01C6)| - |COMBINING GREEK YPOGEGRAMMENI (U+0345)|Uppercase|GREEK CAPITAL LETTER IOTA (U+0399)| - -- Differences in case mappings of two-letter mixed-case pairs in the ASCII character range. In most cultures, a two-letter mixed-case pair is equal to the equivalent two-letter uppercase or lowercase pair. This is not true for the following two-letter pairs in the following cultures, because in each case they are compared to a digraph: - - - "lJ" and "nJ" in the hr-HR (Croatian (Croatia)) culture. - - "cH" in the cs-CZ (Czech (Czech Republic)) and sk-SK (Slovak (Slovakia)) cultures. - - "aA" in the da-DK (Danish (Denmark)) culture. - - "cS", "dZ", "dZS", "nY", "sZ", "tY", and "zS" in the hu-HU (Hungarian (Hungary)) culture. - - "cH" and "lL" in the es-ES_tradnl (Spanish (Spain, Traditional Sort)) culture. - - "cH", "gI", "kH", "nG" "nH", "pH", "qU', "tH", and "tR" in the vi-VN (Vietnamese (Vietnam)) culture. - - However, it is unusual to encounter a situation in which a culture-sensitive comparison of these pairs creates problems, because these pairs are uncommon in fixed strings or identifiers. - -The following example illustrates some of the differences in casing rules between cultures when converting strings to uppercase. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/case1.cs" id="Snippet7"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/case1.fs" id="Snippet7"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/case1.vb" id="Snippet7"::: - -### Parsing and formatting - -Formatting and parsing are inverse operations. Formatting rules determine how to convert a value, such as a date and time or a number, to its string representation, whereas parsing rules determine how to convert a string representation to a value such as a date and time. Both formatting and parsing rules are dependent on cultural conventions. The following example illustrates the ambiguity that can arise when interpreting a culture-specific date string. Without knowing the conventions of the culture that was used to produce a date string, it is not possible to know whether 03/01/2011, 3/1/2011, and 01/03/2011 represent January 3, 2011 or March 1, 2011. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/format1.cs" id="Snippet8"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/format1.fs" id="Snippet8"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/format1.vb" id="Snippet8"::: - -Similarly, as the following example shows, a single string can produce different dates depending on the culture whose conventions are used in the parsing operation. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/parse1.cs" id="Snippet9"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/parse1.fs" id="Snippet9"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/parse1.vb" id="Snippet9"::: - -### String comparison and sorting - -Conventions for comparing and sorting strings vary from culture to culture. For example, the sort order may be based on phonetics or on the visual representation of characters. In East Asian languages, characters are sorted by the stroke and radical of ideographs. Sorting also depends on the order languages and cultures use for the alphabet. For example, the Danish language has an "Æ" character that it sorts after "Z" in the alphabet. In addition, comparisons can be case-sensitive or case-insensitive, and casing rules might differ by culture. Ordinal comparison, on the other hand, uses the Unicode code points of individual characters in a string when comparing and sorting strings. - -Sort rules determine the alphabetic order of Unicode characters and how two strings compare to each other. For example, the method compares two strings based on the parameter. If the parameter value is , the method performs a linguistic comparison that uses the conventions of the current culture; if the parameter value is , the method performs an ordinal comparison. Consequently, as the following example shows, if the current culture is U.S. English, the first call to the method (using culture-sensitive comparison) considers "a" less than "A", but the second call to the same method (using ordinal comparison) considers "a" greater than "A". - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/compare11.cs" id="Snippet10"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/compare11.fs" id="Snippet10"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/compare1.vb" id="Snippet10"::: - -.NET supports word, string, and ordinal sort rules: - -- A word sort performs a culture-sensitive comparison of strings in which certain nonalphanumeric Unicode characters might have special weights assigned to them. For example, the hyphen (-) might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. For a list of the methods that compare two strings using word sort rules, see the [String operations by category](#string-operations-by-category) section. - -- A string sort also performs a culture-sensitive comparison. It is similar to a word sort, except that there are no special cases, and all nonalphanumeric symbols come before all alphanumeric Unicode characters. Two strings can be compared using string sort rules by calling the method overloads that have an `options` parameter that is supplied a value of . Note that this is the only method that .NET provides to compare two strings using string sort rules. - -- An ordinal sort compares strings based on the numeric value of each object in the string. An ordinal comparison is automatically case-sensitive because the lowercase and uppercase versions of a character have different code points. However, if case is not important, you can specify an ordinal comparison that ignores case. This is equivalent to converting the string to uppercase by using the invariant culture and then performing an ordinal comparison on the result. For a list of the methods that compare two strings using ordinal sort rules, see the [String operations by category](#string-operations-by-category) section. - -A culture-sensitive comparison is any comparison that explicitly or implicitly uses a object, including the invariant culture that is specified by the property. The implicit culture is the current culture, which is specified by the and properties. There is considerable variation in the sort order of alphabetic characters (that is, characters for which the method returns `true`) across cultures. You can specify a culture-sensitive comparison that uses the conventions of a specific culture by supplying a object to a string comparison method such as . You can specify a culture-sensitive comparison that uses the conventions of the current culture by supplying , , or any member of the enumeration other than or to an appropriate overload of the method. A culture-sensitive comparison is generally appropriate for sorting whereas an ordinal comparison is not. An ordinal comparison is generally appropriate for determining whether two strings are equal (that is, for determining identity) whereas a culture-sensitive comparison is not. - -The following example illustrates the difference between culture-sensitive and ordinal comparison. The example evaluates three strings, "Apple", "Æble", and "AEble", using ordinal comparison and the conventions of the da-DK and en-US cultures (each of which is the default culture at the time the method is called). Because the Danish language treats the character "Æ" as an individual letter and sorts it after "Z" in the alphabet, the string "Æble" is greater than "Apple". However, "Æble" is not considered equivalent to "AEble", so "Æble" is also greater than "AEble". The en-US culture doesn't include the letter"Æ" but treats it as equivalent to "AE", which explains why "Æble" is less than "Apple" but equal to "AEble". Ordinal comparison, on the other hand, considers "Apple" to be less than "Æble", and "Æble" to be greater than "AEble". - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/compare4.cs" id="Snippet21"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/compare4.fs" id="Snippet21"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/compare4.vb" id="Snippet21"::: - -Use the following general guidelines to choose an appropriate sorting or string comparison method: - -- If you want the strings to be ordered based on the user's culture, you should order them based on the conventions of the current culture. If the user's culture changes, the order of sorted strings will also change accordingly. For example, a thesaurus application should always sort words based on the user's culture. - -- If you want the strings to be ordered based on the conventions of a specific culture, you should order them by supplying a object that represents that culture to a comparison method. For example, in an application designed to teach students a particular language, you want strings to be ordered based on the conventions of one of the cultures that speaks that language. - -- If you want the order of strings to remain unchanged across cultures, you should order them based on the conventions of the invariant culture or use an ordinal comparison. For example, you would use an ordinal sort to organize the names of files, processes, mutexes, or named pipes. - -- For a comparison that involves a security decision (such as whether a username is valid), you should always perform an ordinal test for equality by calling an overload of the method. - -> [!NOTE] -> The culture-sensitive sorting and casing rules used in string comparison depend on the version of the .NET. On .NET Core, string comparison depends on the version of the Unicode Standard supported by the underlying operating system. In .NET Framework 4.5 and later versions running on Windows 8 or later, sorting, casing, normalization, and Unicode character information conform to the Unicode 6.0 standard. On other Windows operating systems, they conform to the Unicode 5.0 standard. - -For more information about word, string, and ordinal sort rules, see the topic. For additional recommendations on when to use each rule, see [Best Practices for Using Strings](../../standard/base-types/best-practices-strings.md). - -Ordinarily, you don't call string comparison methods such as directly to determine the sort order of strings. Instead, comparison methods are called by sorting methods such as or . The following example performs four different sorting operations (word sort using the current culture, word sort using the invariant culture, ordinal sort, and string sort using the invariant culture) without explicitly calling a string comparison method, although they do specify the type of comparison to use. Note that each type of sort produces a unique ordering of strings in its array. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/compare2.cs" id="Snippet12"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/compare2.fs" id="Snippet12"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/compare2.vb" id="Snippet12"::: - -> [!TIP] -> Internally, .NET uses sort keys to support culturally sensitive string comparison. Each character in a string is given several categories of sort weights, including alphabetic, case, and diacritic. A sort key, represented by the class, provides a repository of these weights for a particular string. If your app performs a large number of searching or sorting operations on the same set of strings, you can improve its performance by generating and storing sort keys for all the strings that it uses. When a sort or comparison operation is required, you use the sort keys instead of the strings. For more information, see the class. - -If you don't specify a string comparison convention, sorting methods such as perform a culture-sensitive, case-sensitive sort on strings. The following example illustrates how changing the current culture affects the order of sorted strings in an array. It creates an array of three strings. First, it sets the `System.Threading.Thread.CurrentThread.CurrentCulture` property to en-US and calls the method. The resulting sort order is based on sorting conventions for the English (United States) culture. Next, the example sets the `System.Threading.Thread.CurrentThread.CurrentCulture` property to da-DK and calls the method again. Notice how the resulting sort order differs from the en-US results because it uses the sorting conventions for Danish (Denmark). - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/sort1.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/sort1.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/sort1.vb" id="Snippet3"::: - -> [!WARNING] -> If your primary purpose in comparing strings is to determine whether they are equal, you should call the method. Typically, you should use to perform an ordinal comparison. The method is intended primarily to sort strings. - -String search methods, such as and , also can perform culture-sensitive or ordinal string comparisons. The following example illustrates the differences between ordinal and culture-sensitive comparisons using the method. A culture-sensitive search in which the current culture is English (United States) considers the substring "oe" to match the ligature "œ". Because a soft hyphen (U+00AD) is a zero-width character, the search treats the soft hyphen as equivalent to and finds a match at the beginning of the string. An ordinal search, on the other hand, does not find a match in either case. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/compare3.cs" id="Snippet13"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/compare3.fs" id="Snippet13"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/compare3.vb" id="Snippet13"::: - -### Search in strings - -String search methods, such as and , also can perform culture-sensitive or ordinal string comparisons to determine whether a character or substring is found in a specified string. - -The search methods in the class that search for an individual character, such as the method, or one of a set of characters, such as the method, all perform an ordinal search. To perform a culture-sensitive search for a character, you must call a method such as or . Note that the results of searching for a character using ordinal and culture-sensitive comparison can be very different. For example, a search for a precomposed Unicode character such as the ligature "Æ" (U+00C6) might match any occurrence of its components in the correct sequence, such as "AE" (U+041U+0045), depending on the culture. The following example illustrates the difference between the and methods when searching for an individual character. The ligature "æ" (U+00E6) is found in the string "aerial" when using the conventions of the en-US culture, but not when using the conventions of the da-DK culture or when performing an ordinal comparison. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/search1.cs" id="Snippet22"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/search1.fs" id="Snippet22"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/search1.vb" id="Snippet22"::: - -On the other hand, class methods that search for a string rather than a character perform a culture-sensitive search if search options are not explicitly specified by a parameter of type . The sole exception is , which performs an ordinal search. - -### Test for equality - -Use the method to determine the relationship of two strings in the sort order. Typically, this is a culture-sensitive operation. In contrast, call the method to test for equality. Because the test for equality usually compares user input with some known string, such as a valid user name, a password, or a file system path, it is typically an ordinal operation. - -> [!WARNING] -> It is possible to test for equality by calling the method and determining whether the return value is zero. However, this practice is not recommended. To determine whether two strings are equal, you should call one of the overloads of the method. The preferred overload to call is either the instance method or the static method, because both methods include a parameter that explicitly specifies the type of comparison. - -The following example illustrates the danger of performing a culture-sensitive comparison for equality when an ordinal one should be used instead. In this case, the intent of the code is to prohibit file system access from URLs that begin with "FILE://" or "file://" by performing a case-insensitive comparison of the beginning of a URL with the string "FILE://". However, if a culture-sensitive comparison is performed using the Turkish (Turkey) culture on a URL that begins with "file://", the comparison for equality fails, because the Turkish uppercase equivalent of the lowercase "i" is "İ" instead of "I". As a result, file system access is inadvertently permitted. On the other hand, if an ordinal comparison is performed, the comparison for equality succeeds, and file system access is denied. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/equality1.cs" id="Snippet11"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/equality1.fs" id="Snippet11"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/equality1.vb" id="Snippet11"::: - -## Normalization - -Some Unicode characters have multiple representations. For example, any of the following code points can represent the letter "ắ": - -- U+1EAF -- U+0103 U+0301 -- U+0061 U+0306 U+0301 - -Multiple representations for a single character complicate searching, sorting, matching, and other string operations. - -The Unicode standard defines a process called normalization that returns one binary representation of a Unicode character for any of its equivalent binary representations. Normalization can use several algorithms, called normalization forms, that follow different rules. .NET supports Unicode normalization forms C, D, KC, and KD. When strings have been normalized to the same normalization form, they can be compared by using ordinal comparison. - -An ordinal comparison is a binary comparison of the Unicode scalar value of corresponding objects in each string. The class includes a number of methods that can perform an ordinal comparison, including the following: - -- Any overload of the , , , , , and methods that includes a parameter. The method performs an ordinal comparison if you supply a value of or for this parameter. - -- The overloads of the method. - -- Methods that use ordinal comparison by default, such as , , and . - -- Methods that search for a value or for the elements in a array in a string instance. Such methods include and . - -You can determine whether a string is normalized to normalization form C by calling the method, or you can call the method to determine whether a string is normalized to a specified normalization form. You can also call the method to convert a string to normalization form C, or you can call the method to convert a string to a specified normalization form. For step-by-step information about normalizing and comparing strings, see the and methods. - -The following simple example illustrates string normalization. It defines the letter "ố" in three different ways in three different strings, and uses an ordinal comparison for equality to determine that each string differs from the other two strings. It then converts each string to the supported normalization forms, and again performs an ordinal comparison of each string in a specified normalization form. In each case, the second test for equality shows that the strings are equal. - -:::code language="csharp" source="./snippets/System/String/Overview/csharp/normalize1.cs" id="Snippet14"::: -:::code language="fsharp" source="./snippets/System/String/Overview/fsharp/normalize1.fs" id="Snippet14"::: -:::code language="vb" source="./snippets/System/String/Overview/vb/normalize1.vb" id="Snippet14"::: - -For more information about normalization and normalization forms, see , as well as [Unicode Standard Annex #15: Unicode Normalization Forms](https://unicode.org/reports/tr15/) and the [Normalization FAQ](https://www.unicode.org/faq/normalization.html) on the unicode.org website. - -## String operations by category - -The class provides members for comparing strings, testing strings for equality, finding characters or substrings in a string, modifying a string, extracting substrings from a string, combining strings, formatting values, copying a string, and normalizing a string. - -### Compare strings - -You can compare strings to determine their relative position in the sort order by using the following methods: - -- returns an integer that indicates the relationship of one string to a second string in the sort order. - -- returns an integer that indicates the relationship of one string to a second string based on a comparison of their code points. - -- returns an integer that indicates the relationship of the current string instance to a second string in the sort order. The method provides the and implementations for the class. - -### Test strings for equality - -You call the method to determine whether two strings are equal. The instance and the static overloads let you specify whether the comparison is culture-sensitive or ordinal, and whether case is considered or ignored. Most tests for equality are ordinal, and comparisons for equality that determine access to a system resource (such as a file system object) should always be ordinal. - -### Find characters in a string - -The class includes two kinds of search methods: - -- Methods that return a value to indicate whether a particular substring is present in a string instance. These include the , , and methods. - -- Methods that indicate the starting position of a substring in a string instance. These include the , , , and methods. - -> [!WARNING] -> If you want to search a string for a particular pattern rather than a specific substring, you should use regular expressions. For more information, see [.NET Regular Expressions](../../standard/base-types/regular-expressions.md). - -### Modify a string - -The class includes the following methods that appear to modify the value of a string: - -- inserts a string into the current instance. - -- inserts one or more occurrences of a specified character at the beginning of a string. - -- inserts one or more occurrences of a specified character at the end of a string. - -- deletes a substring from the current instance. - -- replaces a substring with another substring in the current instance. - -- and convert all the characters in a string to lowercase. - -- and convert all the characters in a string to uppercase. - -- removes all occurrences of a character from the beginning and end of a string. - -- removes all occurrences of a character from the end of a string. - -- removes all occurrences of a character from the beginning of a string. - -> [!IMPORTANT] -> All string modification methods return a new object. They don't modify the value of the current instance. - -### Extract substrings from a string - -The method separates a single string into multiple strings. Overloads of the method allow you to specify multiple delimiters, to limit the number of substrings that the method extracts, to trim white space from substrings, and to specify whether empty strings (which occur when delimiters are adjacent) are included among the returned strings. - -### Combine strings - -The following methods can be used for string concatenation: - -- combines one or more substrings into a single string. -- concatenates one or more substrings into a single element and adds a separator between each substring. - -### Format values - -The method uses the composite formatting feature to replace one or more placeholders in a string with the string representation of some object or value. The method is often used to do the following: - -- To embed the string representation of a numeric value in a string. -- To embed the string representation of a date and time value in a string. -- To embed the string representation of an enumeration value in a string. -- To embed the string representation of some object that supports the interface in a string. -- To right-justify or left-justify a substring in a field within a larger string. - -For detailed information about formatting operations and examples, see the overload summary. - -### Copy a string - -You can call the following methods to make a copy of a string: - -- returns a reference to an existing object. -- copies a portion of a string to a character array. - -### Normalize a string - -In Unicode, a single character can have multiple code points. Normalization converts these equivalent characters into the same binary representation. The method performs the normalization, and the method determines whether a string is normalized. - -For more information and an example, see the [Normalization](#normalization) section earlier in this article. diff --git a/docs/fundamentals/runtime-libraries/system-stringcomparer.md b/docs/fundamentals/runtime-libraries/system-stringcomparer.md deleted file mode 100644 index 103cf074bd023..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-stringcomparer.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: System.StringComparer class -description: Learn about the System.StringComparer class. -ms.date: 12/31/2023 ---- -# System.StringComparer class - -[!INCLUDE [context](includes/context.md)] - -An object derived from the class embodies string-based comparison, equality, and hash code operations that take into account both case and culture-specific comparison rules. You can use the class to create a type-specific comparison to sort the elements in a generic collection. Classes such as , , , and use the class for sorting purposes. - -A comparison operation that is represented by the class is defined to be either case-sensitive or case-insensitive, and use either word (culture-sensitive) or ordinal (culture-insensitive) comparison rules. For more information about word and ordinal comparison rules, see . - -> [!NOTE] -> You can download the [Default Unicode Collation Element Table](https://www.unicode.org/Public/UCA/latest/allkeys.txt), the latest version of the sort weight table. The specific version of the sort weight table depends on the version of the [International Components for Unicode](https://icu.unicode.org/) libraries installed on the system. For information on ICU versions and the Unicode versions that they implement, see [Downloading ICU](https://icu.unicode.org/download). -> -> For .NET Framework on Windows, you can download the [Sorting Weight Tables](https://www.microsoft.com/download/details.aspx?id=10921), a set of text files that contain information on the character weights used in sorting and comparison operations. - -## Implemented properties - -You might be confused about how to use the class properties because of a seeming contradiction. The class is declared `abstract` (`MustInherit` in Visual Basic), which means its members can be invoked only on an object of a class derived from the class. The contradiction is that each property of the class is declared `static` (`Shared` in Visual Basic), which means the property can be invoked without first creating a derived class. - -You can call a property directly because each property actually returns an instance of an anonymous class that is derived from the class. Consequently, the type of each property value is , which is the base class of the anonymous class, not the type of the anonymous class itself. Each class property returns a object that supports predefined case and comparison rules. diff --git a/docs/fundamentals/runtime-libraries/system-text-encoding-default.md b/docs/fundamentals/runtime-libraries/system-text-encoding-default.md deleted file mode 100644 index 533fef39f12d2..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-text-encoding-default.md +++ /dev/null @@ -1,19 +0,0 @@ ---- -title: System.Text.Encoding.Default property -description: Learn about the System.Text.Encoding.Default property. -ms.date: 01/24/2024 ---- -# System.Text.Encoding.Default property - -[!INCLUDE [context](includes/context.md)] - -> [!WARNING] -> Different computers can use different encodings as the default, and the default encoding can change on a single computer. If you use the encoding to encode and decode data streamed between computers or retrieved at different times on the same computer, it may translate that data incorrectly. In addition, the encoding returned by the property uses best-fit fallback to map unsupported characters to characters supported by the code page. For these reasons, using the default encoding is not recommended. To ensure that encoded bytes are decoded properly, you should use a Unicode encoding, such as or . You could also use a higher-level protocol to ensure that the same format is used for encoding and decoding. - -## .NET Framework - -In .NET Framework, the property always gets the system's active code page and creates a object that corresponds to it. The active code page may be an ANSI code page, which includes the ASCII character set along with additional characters that vary by code page. Because all encodings based on ANSI code pages lose data, consider using the encoding instead. UTF-8 is often identical in the U+00 to U+7F range, but can encode characters outside the ASCII range without loss. - -## .NET Core - -In .NET Core, the property always returns the . UTF-8 is supported on all the operating systems (Windows, Linux, and macOS) on which .NET Core applications run. diff --git a/docs/fundamentals/runtime-libraries/system-text-encoding.md b/docs/fundamentals/runtime-libraries/system-text-encoding.md deleted file mode 100644 index 46a709d219a9f..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-text-encoding.md +++ /dev/null @@ -1,211 +0,0 @@ ---- -title: System.Text.Encoding class -description: Learn about the System.Text.Encoding class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Text.Encoding class - -[!INCLUDE [context](includes/context.md)] - -The class represents a character encoding. - -Encoding is the process of transforming a set of Unicode characters into a sequence of bytes. In contrast, decoding is the process of transforming a sequence of encoded bytes into a set of Unicode characters. For information about the Unicode Transformation Formats (UTFs) and other encodings supported by , see [Character Encoding in .NET](../../standard/base-types/character-encoding.md). - - is intended to operate on Unicode characters instead of arbitrary binary data, such as byte arrays. If you must encode arbitrary binary data into text, you should use a protocol such as uuencode, which is implemented by methods such as . - -.NET provides the following implementations of the class to support current Unicode encodings and other encodings: - -- encodes Unicode characters as single 7-bit ASCII characters. This encoding only supports character values between U+0000 and U+007F. Code page 20127. Also available through the property. - -- encodes Unicode characters using the UTF-7 encoding. This encoding supports all Unicode character values. Code page 65000. Also available through the property. - -- encodes Unicode characters using the UTF-8 encoding. This encoding supports all Unicode character values. Code page 65001. Also available through the property. - -- encodes Unicode characters using the UTF-16 encoding. Both little endian and big endian byte orders are supported. Also available through the property and the property. - -- encodes Unicode characters using the UTF-32 encoding. Both little endian (code page 12000) and big endian (code page 12001) byte orders are supported. Also available through the property. - -The class is primarily intended to convert between different encodings and Unicode. Often one of the derived Unicode classes is the correct choice for your app. - -Use the method to obtain other encodings, and call the method to get a list of all encodings. - -## List of encodings - -The following table lists the encodings supported by .NET. It lists each encoding's code page number and the values of the encoding's and properties. A check mark in the **.NET Framework support**, **.NET Core support**, or **.NET 5 and later support** column indicates that the code page is natively supported by that .NET implementation, regardless of the underlying platform. For .NET Framework, the availability of other encodings listed in the table depends on the operating system. For .NET Core and .NET 5 and later versions, other encodings are available by using the class or by deriving from the class. - -> [!NOTE] -> Code pages whose property corresponds to an international standard do not necessarily comply in full with that standard. - -|Code page|Name|Display name|.NET Framework support| .NET Core support | .NET 5 and later support | -|---------|----|------------|----------------------|-------------------|----------------------------| -|37|IBM037|IBM EBCDIC (US-Canada)|||| -|437|IBM437|OEM United States|||| -|500|IBM500|IBM EBCDIC (International)|||| -|708|ASMO-708|Arabic (ASMO 708)|||| -|720|DOS-720|Arabic (DOS)|||| -|737|ibm737|Greek (DOS)|||| -|775|ibm775|Baltic (DOS)|||| -|850|ibm850|Western European (DOS)|||| -|852|ibm852|Central European (DOS)|||| -|855|IBM855|OEM Cyrillic|||| -|857|ibm857|Turkish (DOS)|||| -|858|IBM00858|OEM Multilingual Latin I|||| -|860|IBM860|Portuguese (DOS)|||| -|861|ibm861|Icelandic (DOS)|||| -|862|DOS-862|Hebrew (DOS)|||| -|863|IBM863|French Canadian (DOS)|||| -|864|IBM864|Arabic (864)|||| -|865|IBM865|Nordic (DOS)|||| -|866|cp866|Cyrillic (DOS)|||| -|869|ibm869|Greek, Modern (DOS)|||| -|870|IBM870|IBM EBCDIC (Multilingual Latin-2)|||| -|874|windows-874|Thai (Windows)|||| -|875|cp875|IBM EBCDIC (Greek Modern)|||| -|932|shift_jis|Japanese (Shift-JIS)|||| -|936|gb2312|Chinese Simplified (GB2312)|✓||| -|949|ks_c_5601-1987|Korean|||| -|950|big5|Chinese Traditional (Big5)|||| -|1026|IBM1026|IBM EBCDIC (Turkish Latin-5)|||| -|1047|IBM01047|IBM Latin-1|||| -|1140|IBM01140|IBM EBCDIC (US-Canada-Euro)|||| -|1141|IBM01141|IBM EBCDIC (Germany-Euro)|||| -|1142|IBM01142|IBM EBCDIC (Denmark-Norway-Euro)|||| -|1143|IBM01143|IBM EBCDIC (Finland-Sweden-Euro)|||| -|1144|IBM01144|IBM EBCDIC (Italy-Euro)|||| -|1145|IBM01145|IBM EBCDIC (Spain-Euro)|||| -|1146|IBM01146|IBM EBCDIC (UK-Euro)|||| -|1147|IBM01147|IBM EBCDIC (France-Euro)|||| -|1148|IBM01148|IBM EBCDIC (International-Euro)|||| -|1149|IBM01149|IBM EBCDIC (Icelandic-Euro)|||| -|1200|utf-16|Unicode|✓|✓|✓| -|1201|unicodeFFFE|Unicode (Big endian)|✓|✓|✓| -|1250|windows-1250|Central European (Windows)|||| -|1251|windows-1251|Cyrillic (Windows)|||| -|1252|Windows-1252|Western European (Windows)|✓||| -|1253|windows-1253|Greek (Windows)|||| -|1254|windows-1254|Turkish (Windows)|||| -|1255|windows-1255|Hebrew (Windows)|||| -|1256|windows-1256|Arabic (Windows)|||| -|1257|windows-1257|Baltic (Windows)|||| -|1258|windows-1258|Vietnamese (Windows)|||| -|1361|Johab|Korean (Johab)|||| -|10000|macintosh|Western European (Mac)|||| -|10001|x-mac-japanese|Japanese (Mac)|||| -|10002|x-mac-chinesetrad|Chinese Traditional (Mac)|||| -|10003|x-mac-korean|Korean (Mac)|✓||| -|10004|x-mac-arabic|Arabic (Mac)|||| -|10005|x-mac-hebrew|Hebrew (Mac)|||| -|10006|x-mac-greek|Greek (Mac)|||| -|10007|x-mac-cyrillic|Cyrillic (Mac)|||| -|10008|x-mac-chinesesimp|Chinese Simplified (Mac)|✓||| -|10010|x-mac-romanian|Romanian (Mac)|||| -|10017|x-mac-ukrainian|Ukrainian (Mac)|||| -|10021|x-mac-thai|Thai (Mac)|||| -|10029|x-mac-ce|Central European (Mac)|||| -|10079|x-mac-icelandic|Icelandic (Mac)|||| -|10081|x-mac-turkish|Turkish (Mac)|||| -|10082|x-mac-croatian|Croatian (Mac)|||| -|12000|utf-32|Unicode (UTF-32)|✓|✓|✓| -|12001|utf-32BE|Unicode (UTF-32 Big endian)|✓|✓|✓| -|20000|x-Chinese-CNS|Chinese Traditional (CNS)|||| -|20001|x-cp20001|TCA Taiwan|||| -|20002|x-Chinese-Eten|Chinese Traditional (Eten)|||| -|20003|x-cp20003|IBM5550 Taiwan|||| -|20004|x-cp20004|TeleText Taiwan|||| -|20005|x-cp20005|Wang Taiwan|||| -|20105|x-IA5|Western European (IA5)|||| -|20106|x-IA5-German|German (IA5)|||| -|20107|x-IA5-Swedish|Swedish (IA5)|||| -|20108|x-IA5-Norwegian|Norwegian (IA5)|||| -|20127|us-ascii|US-ASCII|✓|✓|✓| -|20261|x-cp20261|T.61|||| -|20269|x-cp20269|ISO-6937|||| -|20273|IBM273|IBM EBCDIC (Germany)|||| -|20277|IBM277|IBM EBCDIC (Denmark-Norway)|||| -|20278|IBM278|IBM EBCDIC (Finland-Sweden)|||| -|20280|IBM280|IBM EBCDIC (Italy)|||| -|20284|IBM284|IBM EBCDIC (Spain)|||| -|20285|IBM285|IBM EBCDIC (UK)|||| -|20290|IBM290|IBM EBCDIC (Japanese katakana)|||| -|20297|IBM297|IBM EBCDIC (France)|||| -|20420|IBM420|IBM EBCDIC (Arabic)|||| -|20423|IBM423|IBM EBCDIC (Greek)|||| -|20424|IBM424|IBM EBCDIC (Hebrew)|||| -|20833|x-EBCDIC-KoreanExtended|IBM EBCDIC (Korean Extended)|||| -|20838|IBM-Thai|IBM EBCDIC (Thai)|||| -|20866|koi8-r|Cyrillic (KOI8-R)|||| -|20871|IBM871|IBM EBCDIC (Icelandic)|||| -|20880|IBM880|IBM EBCDIC (Cyrillic Russian)|||| -|20905|IBM905|IBM EBCDIC (Turkish)|||| -|20924|IBM00924|IBM Latin-1|||| -|20932|EUC-JP|Japanese (JIS 0208-1990 and 0212-1990)|||| -|20936|x-cp20936|Chinese Simplified (GB2312-80)|✓||| -|20949|x-cp20949|Korean Wansung|✓||| -|21025|cp1025|IBM EBCDIC (Cyrillic Serbian-Bulgarian)|||| -|21866|koi8-u|Cyrillic (KOI8-U)|||| -|28591|iso-8859-1|Western European (ISO)|✓|✓|✓| -|28592|iso-8859-2|Central European (ISO)|||| -|28593|iso-8859-3|Latin 3 (ISO)|||| -|28594|iso-8859-4|Baltic (ISO)|||| -|28595|iso-8859-5|Cyrillic (ISO)|||| -|28596|iso-8859-6|Arabic (ISO)|||| -|28597|iso-8859-7|Greek (ISO)|||| -|28598|iso-8859-8|Hebrew (ISO-Visual)|✓||| -|28599|iso-8859-9|Turkish (ISO)|||| -|28603|iso-8859-13|Estonian (ISO)|||| -|28605|iso-8859-15|Latin 9 (ISO)|||| -|29001|x-Europa|Europa|||| -|38598|iso-8859-8-i|Hebrew (ISO-Logical)|✓||| -|50220|iso-2022-jp|Japanese (JIS)|✓||| -|50221|csISO2022JP|Japanese (JIS-Allow 1 byte Kana)|✓||| -|50222|iso-2022-jp|Japanese (JIS-Allow 1 byte Kana - SO/SI)|✓||| -|50225|iso-2022-kr|Korean (ISO)|✓||| -|50227|x-cp50227|Chinese Simplified (ISO-2022)|✓||| -|51932|euc-jp|Japanese (EUC)|✓||| -|51936|EUC-CN|Chinese Simplified (EUC)|✓||| -|51949|euc-kr|Korean (EUC)|✓||| -|52936|hz-gb-2312|Chinese Simplified (HZ)|✓||| -|54936|GB18030|Chinese Simplified (GB18030)|✓||| -|57002|x-iscii-de|ISCII Devanagari|✓||| -|57003|x-iscii-be|ISCII Bengali|✓||| -|57004|x-iscii-ta|ISCII Tamil|✓||| -|57005|x-iscii-te|ISCII Telugu|✓||| -|57006|x-iscii-as|ISCII Assamese|✓||| -|57007|x-iscii-or|ISCII Oriya|✓||| -|57008|x-iscii-ka|ISCII Kannada|✓||| -|57009|x-iscii-ma|ISCII Malayalam|✓||| -|57010|x-iscii-gu|ISCII Gujarati|✓||| -|57011|x-iscii-pa|ISCII Punjabi|✓||| -|65000|utf-7|Unicode (UTF-7)|✓|✓|| -|65001|utf-8|Unicode (UTF-8)|✓|✓|✓| - -The following example calls the and methods to get the Greek (Windows) code page encoding. It compares the objects returned by the method calls to show that they are equal, and then maps displays the Unicode code point and the corresponding code page value for each character in the Greek alphabet. - -:::code language="csharp" source="./snippets/System.Text/Encoding/Overview/csharp/getencoding1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Text/Encoding/Overview/vb/getencoding1.vb" id="Snippet1"::: - -If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, you should use the or the provided by the method or the method, respectively, of a derived class. - -The UTF-16 and the UTF-32 encoders can use the big endian byte order (most significant byte first) or the little endian byte order (least significant byte first). For example, the Latin Capital Letter A (U+0041) is serialized as follows (in hexadecimal): - -- UTF-16 big endian byte order: 00 41 -- UTF-16 little endian byte order: 41 00 -- UTF-32 big endian byte order: 00 00 00 41 -- UTF-32 little endian byte order: 41 00 00 00 - -It is generally more efficient to store Unicode characters using the native byte order. For example, it is better to use the little endian byte order on little endian platforms, such as Intel computers. - -The method retrieves an array of bytes that includes the byte order mark (BOM). If this byte array is prefixed to an encoded stream, it helps the decoder to identify the encoding format used. - -For more information on byte order and the byte order mark, see The Unicode Standard at the [Unicode home page](https://home.unicode.org/). - -Note that the encoding classes allow errors to: - -- Silently change to a "?" character. -- Use a "best fit" character. -- Change to an application-specific behavior through use of the and classes with the U+FFFD Unicode replacement character. - -You should throw an exception on any data stream error. An app either uses a "throwonerror" flag when applicable or uses the and classes. Best fit fallback is often not recommended because it can cause data loss or confusion and is slower than simple character replacements. For ANSI encodings, the best fit behavior is the default. diff --git a/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex-match.md b/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex-match.md deleted file mode 100644 index 644f96afc648b..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex-match.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: System.Text.RegularExpressions.Regex.Match method -description: Learn about the System.Text.RegularExpressions.Regex.Match method. -ms.date: 01/24/2024 ---- -# System.Text.RegularExpressions.Regex.Match method - -[!INCLUDE [context](includes/context.md)] - -The method returns the first substring that matches a regular expression pattern, starting at or after the `startat` character position, in an input string. The regular expression pattern for which the method searches is defined by the call to one of the class constructors. For information about the language elements used to build a regular expression pattern, see [Regular Expression Language - Quick Reference](../../standard/base-types/regular-expression-language-quick-reference.md). - -## The `startat` parameter - -You can optionally specify a starting position in the string by using the `startat` parameter. Any matches starting before `startat` in the string are ignored. If you don't specify a starting position, the search begins at the default position, which is the left end of `input` in a left-to-right search, and the right end of `input` in a right-to-left search. Despite starting at `startat`, the index of any returned match is relative to the start of the string. - -Although the regular expression engine doesn't return any match starting before `startat`, it doesn't ignore the string before `startat`. This means that assertions such as [anchors](../../standard/base-types/anchors-in-regular-expressions.md) or [lookbehind assertions](../../standard/base-types/backtracking-in-regular-expressions.md#lookbehind-assertions) still apply to the input as a whole. For example, the following code includes a pattern with a lookbehind assertion that's satisfied even though it occurs before the `startat` index of 5 in the input string. - -:::code language="csharp" source="./snippets/System.Text.RegularExpressions/Regex/Match/csharp/startat.cs"::: - -> [!TIP] -> -> - If a pattern starts with the `^` anchor but `startat` is greater than 0, no matches will ever be found in a single-line search since they are constrained by `^` to start at index 0. -> - The [`\G` anchor](../../standard/base-types/anchors-in-regular-expressions.md#contiguous-matches-g) is satisfied at `startat`. Because of this, if you want to restrict a match so that it begins exactly at a particular character position in the string, anchor the regular expression with a `\G` on the left for a left-to-right pattern. This restricts the match so it must start exactly at `startat` (or, when multiple matches are desired, so the matches are contiguous). - -## Right-to-left searches - -A right-to-left search, that is, when the regular expression pattern is constructed with the option, behaves in the following ways: - -- The scan moves in the opposite direction and the pattern is matched from back (right) to front (left). -- The default starting position is the right end of the input string. -- If `startat` is specified, the right-to-left scan begins at the character at `startat` - 1 (not `startat`). -- When the `\G` anchor is specified at the right end of a pattern, it restricts the (first) match to end exactly at `startat` - 1. - -For more information about right-to-left searches, see [Right-to-left mode](../../standard/base-types/regular-expression-options.md#right-to-left-mode). - -## Determine whether a match is found - -You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned object's property. If a match is found, the returned object's property contains the substring from `input` that matches the regular expression pattern. If no match is found, its value is . - -## First or multiple matches - -This method returns the first substring found at or after the `startat` character position in `input` that matches the regular expression pattern. You can retrieve subsequent matches by repeatedly calling the returned object's method. You can also retrieve all matches in a single method call by calling the method. - -## Time-out exceptions - -The exception is thrown if the execution time of the matching operation exceeds the time-out interval specified by the constructor. If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the object is created. If no time-out is defined in the constructor call or in the application domain's properties, or if the time-out value is , no exception is thrown. diff --git a/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex.md b/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex.md deleted file mode 100644 index 79a03d4bbdd26..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-text-regularexpressions-regex.md +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: System.Text.RegularExpressions.Regex class -description: Learn about the System.Text.RegularExpressions.Regex class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Text.RegularExpressions.Regex class - -[!INCLUDE [context](includes/context.md)] - -The class represents .NET's regular expression engine. You can use this class to: - -- Quickly parse large amounts of text to find specific character patterns. -- Extract, edit, replace, or delete text substrings. -- Add the extracted strings to a collection to generate a report. - -> [!NOTE] -> If you want to validate a string by determining whether it conforms to a particular regular expression pattern, you can use the class. - -To use regular expressions, you define the pattern that you want to identify in a text stream by using the syntax documented in [Regular expression language - quick reference](../../standard/base-types/regular-expression-language-quick-reference.md). Next, you can optionally instantiate a object. Finally, you call a method that performs some operation, such as replacing text that matches the regular expression pattern, or identifying a pattern match. - -> [!IMPORTANT] -> The regular expression engine assumes that patterns are trusted. Do not pass patterns from untrusted sources to methods. Untrusted patterns can cause excessive resource consumption regardless of the input text. If your application needs to accept search expressions from users, use a restricted syntax that you translate into a regex pattern, or use to treat user input as a literal string. For more information, see [Best Practices for Regular Expressions - Use trusted patterns](../../standard/base-types/best-practices-regex.md#use-trusted-patterns). - -For more information about the regular expression language, see [Regular expression language - quick reference](../../standard/base-types/regular-expression-language-quick-reference.md) or download and print one of these brochures: - -[Quick Reference in Word (.docx) format](https://download.microsoft.com/download/D/2/4/D240EBF6-A9BA-4E4F-A63F-AEB6DA0B921C/Regular%20expressions%20quick%20reference.docx) -[Quick Reference in PDF (.pdf) format](https://download.microsoft.com/download/D/2/4/D240EBF6-A9BA-4E4F-A63F-AEB6DA0B921C/Regular%20expressions%20quick%20reference.pdf) - -## Regex vs. String methods - -The class includes several search and comparison methods that you can use to perform pattern matching with text. For example, the , , and methods determine whether a string instance contains a specified substring; and the , , , and methods return the starting position of a specified substring in a string. Use the methods of the class when you are searching for a specific string. Use the class when you are searching for a specific pattern in a string. For more information and examples, see [.NET Regular Expressions](../../standard/base-types/regular-expressions.md). - -## Static vs. instance methods - -After you define a regular expression pattern, you can provide it to the regular expression engine in either of two ways: - -- By instantiating a object that represents the regular expression. To do this, you pass the regular expression pattern to a constructor. A object is immutable; when you instantiate a object with a regular expression, that object's regular expression cannot be changed. - -- By supplying both the regular expression and the text to search to a `static` (`Shared` in Visual Basic) method. This enables you to use a regular expression without explicitly creating a object. - -All pattern identification methods include both static and instance overloads. - -The regular expression engine must compile a particular pattern before the pattern can be used. Because objects are immutable, this is a one-time procedure that occurs when a class constructor or a static method is called. To eliminate the need to repeatedly compile a single regular expression, the regular expression engine caches the compiled regular expressions used in static method calls. As a result, regular expression pattern-matching methods offer comparable performance for static and instance methods. However, caching can adversely affect performance in the following two cases: - -- When you use static method calls with a large number of regular expressions. By default, the regular expression engine caches the 15 most recently used static regular expressions. If your application uses more than 15 static regular expressions, some regular expressions must be recompiled. To prevent this recompilation, you can increase the property. - -- When you instantiate new objects with regular expressions that have previously been compiled. For example, the following code defines a regular expression to locate duplicated words in a text stream. Although the example uses a single regular expression, it instantiates a new object to process each line of text. This results in the recompilation of the regular expression with each iteration of the loop. - - :::code language="csharp" source="./snippets/System.Text.RegularExpressions/Regex/Overview/csharp/caching1.cs" id="Snippet1"::: - :::code language="vb" source="./snippets/System.Text/RegularExpressions/Overview/vb/caching1.vb" id="Snippet1"::: - - To prevent recompilation, you should instantiate a single object that is accessible to all code that requires it, as shown in the following rewritten example. - - :::code language="csharp" source="./snippets/System.Text.RegularExpressions/Regex/Overview/csharp/caching1.cs" id="Snippet2"::: - :::code language="vb" source="./snippets/System.Text/RegularExpressions/Overview/vb/caching1.vb" id="Snippet2"::: - -## Perform regular expression operations - -Whether you decide to instantiate a object and call its methods or call static methods, the class offers the following pattern-matching functionality: - -- Validation of a match. You call the method to determine whether a match is present. - -- Retrieval of a single match. You call the method to retrieve a object that represents the first match in a string or in part of a string. Subsequent matches can be retrieved by calling the method. - -- Retrieval of all matches. You call the method to retrieve a object that represents all the matches found in a string or in part of a string. - -- Replacement of matched text. You call the method to replace matched text. The replacement text can also be defined by a regular expression. In addition, some of the methods include a parameter that enables you to programmatically define the replacement text. - -- Creation of a string array that is formed from parts of an input string. You call the method to split an input string at positions that are defined by the regular expression. - -In addition to its pattern-matching methods, the class includes several special-purpose methods: - -- The method escapes any characters that may be interpreted as regular expression operators in a regular expression or input string. -- The method removes these escape characters. -- The method creates an assembly that contains predefined regular expressions. .NET contains examples of these special-purpose assemblies in the namespace. - -## Define a time-out value - -.NET supports a full-featured regular expression language that provides substantial power and flexibility in pattern matching. However, the power and flexibility come at a cost: the risk of poor performance. Regular expressions that perform poorly are surprisingly easy to create. In some cases, regular expression operations that rely on excessive backtracking can appear to stop responding when they process text that nearly matches the regular expression pattern. For more information about the .NET Regular Expression engine, see [Details of regular expression behavior](../../standard/base-types/details-of-regular-expression-behavior.md). For more information about excessive backtracking, see [Backtracking](../../standard/base-types/backtracking-in-regular-expressions.md). - -Starting with .NET Framework 4.5, you can define a time-out interval for regular expression matches to limit excessive backtracking. Depending on the regular expression pattern and the input text, the execution time may exceed the specified time-out interval, but it will not spend more time backtracking than the specified time-out interval. If the regular expression engine times out, it throws a exception. In most cases, this prevents the regular expression engine from wasting processing power by trying to match text that nearly matches the regular expression pattern. It also could indicate, however, that the time-out interval has been set too low, or that the current machine load has caused an overall degradation in performance. - -How you handle the exception depends on the cause of the exception. If the exception occurs because the time-out interval is set too low or because of excessive machine load, you can increase the time-out interval and retry the matching operation. If the exception occurs because the regular expression relies on excessive backtracking, you can assume that a match does not exist, and, optionally, you can log information that will help you modify the regular expression pattern. - -You can set a time-out interval by calling the constructor when you instantiate a regular expression object. For static methods, you can set a time-out interval by calling an overload of a matching method that has a `matchTimeout` parameter. If you do not set a time-out value explicitly, the default time-out value is determined as follows: - -- By using the application-wide time-out value, if one exists. Set the application-wide time-out value by calling the method to assign the string representation of a value to the `REGEX_DEFAULT_MATCH_TIMEOUT` property. -- By using the value , if no application-wide time-out value has been set. - -> [!IMPORTANT] -> We recommend that you set a time-out value in all regular expression pattern-matching operations. For more information, see [Best practices for regular expressions](../../standard/base-types/best-practices-regex.md). - -## Examples - -The following example uses a regular expression to check for repeated occurrences of words in a string. The regular expression `\b(?\w+)\s+(\k)\b` can be interpreted as shown in the following table. - -| Pattern | Description | -|----------------|-------------------------------------------------------------------------------------------| -| `\b` | Start the match at a word boundary. | -| `(?\w+)` | Match one or more word characters up to a word boundary. Name this captured group `word`. | -| `\s+` | Match one or more white-space characters. | -| `(\k)` | Match the captured group that's named `word`. | -| `\b` | Match a word boundary. | - -:::code language="csharp" source="./snippets/System.Text.RegularExpressions/Regex/Overview/csharp/words.cs" id="Snippet0"::: -:::code language="vb" source="./snippets/System.Text.RegularExpressions/Regex/Overview/vb/words.vb" id="Snippet0"::: - -The next example illustrates the use of a regular expression to check whether a string either represents a currency value or has the correct format to represent a currency value. In this case, the regular expression is built dynamically from the , , , , and properties for the en-US culture. The resulting regular expression is `^\s*[\+-]?\s?\$?\s?(\d*\.?\d{2}?){1}$`. This regular expression can be interpreted as shown in the following table. - -| Pattern | Description | -|------------|--------------------------------------------------------------------------------| -| `^` | Start at the beginning of the string. | -| `\s*` | Match zero or more white-space characters. | -| `[\+-]?` | Match zero or one occurrence of either the positive sign or the negative sign. | -| `\s?` | Match zero or one white-space character. | -| `\$?` | Match zero or one occurrence of the dollar sign. | -| `\s?` | Match zero or one white-space character. | -| `\d*` | Match zero or more decimal digits. | -| `\.?` | Match zero or one decimal point symbol. | -| `(\d{2})?` | Capturing group 1: Match two decimal digits zero or one time. | -| `(\d*\.?(\d{2})?){1}` | Match the pattern of integral and fractional digits separated by a decimal point symbol exactly once. | -| `$` | Match the end of the string. | - -In this case, the regular expression assumes that a valid currency string does not contain group separator symbols, and that it has either no fractional digits or the number of fractional digits defined by the specified culture's property. - -:::code language="csharp" source="./snippets/System.Text.RegularExpressions/Regex/Overview/csharp/regex_example1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Text.RegularExpressions/Regex/Overview/vb/regex_example1.vb" id="Snippet1"::: - -Because the regular expression in this example is built dynamically, you don't know at design time whether the currency symbol, decimal sign, or positive and negative signs of the specified culture (en-US in this example) might be misinterpreted by the regular expression engine as regular expression language operators. To prevent any misinterpretation, the example passes each dynamically generated string to the method. diff --git a/docs/fundamentals/runtime-libraries/system-text-rune.md b/docs/fundamentals/runtime-libraries/system-text-rune.md deleted file mode 100644 index 166dd38c48112..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-text-rune.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: System.Text.Rune class -description: Learn about the System.Text.Rune class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp ---- -# System.Text.Rune struct - -[!INCLUDE [context](includes/context.md)] - -A instance represents a Unicode scalar value, which means any code point excluding the surrogate range (U+D800..U+DFFF). The type's constructors and conversion operators validate the input, so consumers can call the APIs assuming that the underlying instance is well formed. - -If you aren't familiar with the terms Unicode scalar value, code point, surrogate range, and well-formed, see [Introduction to character encoding in .NET](../../standard/base-types/character-encoding-introduction.md). - -## When to use the Rune type - -Consider using the `Rune` type if your code: - -* Calls APIs that require Unicode scalar values -* Explicitly handles surrogate pairs - -### APIs that require Unicode scalar values - -If your code iterates through the `char` instances in a `string` or a `ReadOnlySpan`, some of the `char` methods won't work correctly on `char` instances that are in the surrogate range. For example, the following APIs require a scalar value `char` to work correctly: - -* -* -* -* -* -* -* -* -* -* - -The following example shows code that won't work correctly if any of the `char` instances are surrogate code points: - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/CountLettersInString.cs" id="SnippetBadExample"::: -:::code language="fsharp" source="./snippets/System.Text/Rune/Overview/fsharp/CountLettersInString.fs" id="SnippetBadExample"::: - -Here's equivalent code that works with a `ReadOnlySpan`: - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/CountLettersInSpan.cs" id="SnippetBadExample"::: - -The preceding code works correctly with some languages such as English: - -```csharp -CountLettersInString("Hello") -// Returns 5 -``` - -But it won't work correctly for languages outside the Basic Multilingual Plane, such as Osage: - -```csharp -CountLettersInString("𐓏𐓘𐓻𐓘𐓻𐓟 𐒻𐓟") -// Returns 0 -``` - -The reason this method returns incorrect results for Osage text is that the `char` instances for Osage letters are surrogate code points. No single surrogate code point has enough information to determine if it's a letter. - -If you change this code to use `Rune` instead of `char`, the method works correctly with code points outside the Basic Multilingual Plane: - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/CountLettersInString.cs" id="SnippetGoodExample"::: -:::code language="fsharp" source="./snippets/System.Text/Rune/Overview/fsharp/CountLettersInString.fs" id="SnippetGoodExample"::: - -Here's equivalent code that works with a `ReadOnlySpan`: - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/CountLettersInSpan.cs" id="SnippetGoodExample"::: - -The preceding code counts Osage letters correctly: - -```csharp -CountLettersInString("𐓏𐓘𐓻𐓘𐓻𐓟 𐒻𐓟") -// Returns 8 -``` - -### Code that explicitly handles surrogate pairs - -Consider using the `Rune` type if your code calls APIs that explicitly operate on surrogate code points, such as the following methods: - -* -* -* -* -* -* - -For example, the following method has special logic to deal with surrogate `char` pairs: - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/WorkWithSurrogates.cs" id="SnippetUseChar"::: - -Such code is simpler if it uses `Rune`, as in the following example: - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/WorkWithSurrogates.cs" id="SnippetUseRune"::: - -## When not to use `Rune` - -You don't need to use the `Rune` type if your code: - -* Looks for exact `char` matches -* Splits a string on a known char value - -Using the `Rune` type may return incorrect results if your code: - -* Counts the number of display characters in a `string` - -### Look for exact `char` matches - -The following code iterates through a `string` looking for specific characters, returning the index of the first match. There's no need to change this code to use `Rune`, as the code is looking for characters that are represented by a single `char`. - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/FindFirstLetter.cs" id="SnippetExample"::: - -### Split a string on a known `char` - -It's common to call `string.Split` and use delimiters such as `' '` (space) or `','` (comma), as in the following example: - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/SplitStringOnChar.cs" id="SnippetExample"::: - -There is no need to use `Rune` here, because the code is looking for characters that are represented by a single `char`. - -### Count the number of display characters in a `string` - -The number of `Rune` instances in a string might not match the number of user-perceivable characters shown when displaying the string. - -Since `Rune` instances represent Unicode scalar values, components that follow the [Unicode text segmentation guidelines](https://www.unicode.org/reports/tr29/) can use `Rune` as a building block for counting display characters. - -The type can be used to count display characters, but it doesn't count correctly in all scenarios for .NET implementations other than .NET 5+. - -For more information, see [Grapheme clusters](../../standard/base-types/character-encoding-introduction.md#grapheme-clusters). - -## How to instantiate a `Rune` - -There are several ways to get a `Rune` instance. You can use a constructor to create a `Rune` directly from: - -* A code point. - - :::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/InstantiateRunes.cs" id="SnippetCodePoint"::: - -* A single `char`. - - :::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/InstantiateRunes.cs" id="SnippetChar"::: - -* A surrogate `char` pair. - - :::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/InstantiateRunes.cs" id="SnippetSurrogate"::: - -All of the constructors throw an `ArgumentException` if the input doesn't represent a valid Unicode scalar value. - -There are methods available for callers who don't want exceptions to be thrown on failure. - -`Rune` instances can also be read from existing input sequences. For instance, given a `ReadOnlySpan` that represents UTF-16 data, the method returns the first `Rune` instance at the beginning of the input span. The method operates similarly, accepting a `ReadOnlySpan` parameter that represents UTF-8 data. There are equivalent methods to read from the end of the span instead of the beginning of the span. - -## Query properties of a `Rune` - -To get the integer code point value of a `Rune` instance, use the property. - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/InstantiateRunes.cs" id="SnippetValue"::: - -Many of the static APIs available on the `char` type are also available on the `Rune` type. For instance, and are equivalents to and methods. The `Rune` methods correctly handle surrogate pairs. - -The following example code takes a `ReadOnlySpan` as input and trims from both the start and the end of the span every `Rune` that isn't a letter or a digit. - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/TrimNonLettersAndNonDigits.cs" id="SnippetExample"::: - -There are some API differences between `char` and `Rune`. For example: - -* There is no `Rune` equivalent to , since `Rune` instances by definition can never be surrogate code points. -* The doesn't always return the same result as . It does return the same value as . For more information, see the **Remarks** on . - -## Convert a `Rune` to UTF-8 or UTF-16 - -Since a `Rune` is a Unicode scalar value, it can be converted to UTF-8, UTF-16, or UTF-32 encoding. The `Rune` type has built-in support for conversion to UTF-8 and UTF-16. - -The converts a `Rune` instance to `char` instances. To query the number of `char` instances that would result from converting a `Rune` instance to UTF-16, use the property. Similar methods exist for UTF-8 conversion. - -The following example converts a `Rune` instance to a `char` array. The code assumes you have a `Rune` instance in the `rune` variable: - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/EncodeRune.cs" id="SnippetUtf16CharArray"::: - -Since a `string` is a sequence of UTF-16 chars, the following example also converts a `Rune` instance to UTF-16: - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/EncodeRune.cs" id="SnippetUtf16String"::: - -The following example converts a `Rune` instance to a `UTF-8` byte array: - -:::code language="csharp" source="./snippets/System.Text/Rune/Overview/csharp/EncodeRune.cs" id="SnippetUtf8ByteArray"::: - -The and methods return the actual number of elements written. They throw an exception if the destination buffer is too short to contain the result. There are non-throwing and methods as well for callers who want to avoid exceptions. - -## Rune in .NET vs. other languages - -The term "rune" is not defined in the Unicode Standard. The term dates back to [the creation of UTF-8](https://www.cl.cam.ac.uk/~mgk25/ucs/utf-8-history.txt). Rob Pike and Ken Thompson were looking for a term to describe what would eventually become known as a code point. [They settled on the term "rune"](https://twitter.com/rob_pike/status/732353233474064384), and Rob Pike's later influence over the Go programming language helped popularize the term. - -However, the .NET `Rune` type is not the equivalent of the Go `rune` type. In Go, the `rune` type is an [alias for `int32`](https://blog.golang.org/strings). A Go rune is intended to represent a Unicode code point, but it can be any 32-bit value, including surrogate code points and values that are not legal Unicode code points. - -For similar types in other programming languages, see [Rust's primitive `char` type](https://doc.rust-lang.org/std/primitive.char.html) or [Swift's `Unicode.Scalar` type](https://developer.apple.com/documentation/swift/unicode/scalar), both of which represent Unicode scalar values. They provide functionality similar to .NET's `Rune` type, and they disallow instantiation of values that are not legal Unicode scalar values. diff --git a/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md b/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md deleted file mode 100644 index 3ad1c8253397d..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-text-stringbuilder.md +++ /dev/null @@ -1,207 +0,0 @@ ---- -title: System.Text.StringBuilder class -description: Learn about the System.Text.StringBuilder class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Text.StringBuilder class - -[!INCLUDE [context](includes/context.md)] - -The class represents a string-like object whose value is a mutable sequence of characters. - -## StringBuilder versus String type - -Although and both represent sequences of characters, they are implemented differently. is an immutable type. That is, each operation that appears to modify a object actually creates a new string. - -For example, the call to the method in the following C# example appears to change the value of a string variable named `value`. In fact, the method returns a `value` object that has a different value and address from the `value` object that was passed to the method. Note that the example must be compiled using the `/unsafe` compiler option. - -:::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/immutability2.cs" id="Snippet1"::: -:::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/immutability2.fs" id="Snippet1"::: - -For routines that perform extensive string manipulation (such as apps that modify a string numerous times in a loop), modifying a string repeatedly can exert a significant performance penalty. The alternative is to use , which is a mutable string class. Mutability means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters. - -> [!IMPORTANT] -> Although the class generally offers better performance than the class, you should not automatically replace with whenever you want to manipulate strings. Performance depends on the size of the string, the amount of memory to be allocated for the new string, the system on which your code is executing, and the type of operation. You should be prepared to test your code to determine whether actually offers a significant performance improvement. - -Consider using the class under these conditions: - -- When the number of changes that your code will make to a string is small. In these cases, might offer negligible or no performance improvement over . -- When you perform a fixed number of concatenation operations, particularly with string literals. In this case, the compiler might combine the concatenation operations into a single operation. -- When you have to perform extensive search operations while you are building your string. The class lacks search methods such as `IndexOf` or `StartsWith`. You'll have to convert the object to a for these operations, and this can negate the performance benefit from using . For more information, see the [Search the text in a StringBuilder object](#search-the-text-in-a-stringbuilder-object) section. - -Consider using the class under these conditions: - -- When you expect your code to make an unknown number of changes to a string at design time (for example, when you use a loop to concatenate a random number of strings that contain user input). -- When you expect your code to make a significant number of changes to a string. - -## How StringBuilder works - -The property indicates the number of characters the object currently contains. If you add characters to the object, its length increases until it equals the size of the property, which defines the number of characters that the object can contain. If the number of added characters causes the length of the object to exceed its current capacity, new memory is allocated, the value of the property is doubled, new characters are added to the object, and its property is adjusted. Additional memory for the object is allocated dynamically until it reaches the value defined by the property. When the maximum capacity is reached, no further memory can be allocated for the object, and trying to add characters or expand it beyond its maximum capacity throws either an or an exception. - -The following example illustrates how a object allocates new memory and increases its capacity dynamically as the string assigned to the object expands. The code creates a object by calling its default (parameterless) constructor. The default capacity of this object is 16 characters, and its maximum capacity is more than 2 billion characters. Appending the string "This is a sentence." results in a new memory allocation because the string length (19 characters) exceeds the default capacity of the object. The capacity of the object doubles to 32 characters, the new string is added, and the length of the object now equals 19 characters. The code then appends the string "This is an additional sentence." to the value of the object 11 times. Whenever the append operation causes the length of the object to exceed its capacity, its existing capacity is doubled and the operation succeeds. - -:::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/default1.cs" id="Snippet3"::: -:::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/default1.fs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/default1.vb" id="Snippet3"::: - -## Memory allocation - -The default capacity of a object is 16 characters, and its default maximum capacity is . These default values are used if you call the and constructors. - -You can explicitly define the initial capacity of a object in the following ways: - -- By calling any of the constructors that includes a `capacity` parameter when you create the object. -- By explicitly assigning a new value to the property to expand an existing object. (The property throws an exception if the new capacity is less than the existing capacity or greater than the object's maximum capacity.) -- By calling the method with the new capacity. The new capacity must not be greater than the object's maximum capacity. However, unlike an assignment to the property, does not throw an exception if the desired new capacity is less than the existing capacity. In this case, the method call has no effect. - -If the length of the string assigned to the object in the constructor call exceeds either the default capacity or the specified capacity, the property is set to the length of the string specified with the `value` parameter. - -You can explicitly define the maximum capacity of a object by calling the constructor. You can't change the maximum capacity by assigning a new value to the property, because it is read-only. - -As the previous section shows, whenever the existing capacity is inadequate, additional memory is allocated and the capacity of a object doubles up to the value defined by the property. - -In general, the default capacity and maximum capacity are adequate for most apps. You might consider setting these values under the following conditions: - -- If the eventual size of the object is likely to grow exceedingly large, typically in excess of several megabytes. In this case, there might be some performance benefit from setting the initial property to a significantly high value to eliminate the need for too many memory reallocations. -- If your code is running on a system with limited memory. In this case, you might consider setting the property to less than if your code is handling large strings that might cause it to execute in a memory-constrained environment. - -## Instantiate a StringBuilder object - -You instantiate a object by calling one of its six overloaded class constructors, which are listed in the following table. Three of the constructors instantiate a object whose value is an empty string, but set its and values differently. The remaining three constructors define a object that has a specific string value and capacity. Two of the three constructors use the default maximum capacity of , whereas the third allows you to set the maximum capacity. - -| Constructor | String value | Capacity | Maximum capacity | -|-------------|--------------|----------|------------------| -|||16|| -|||Defined by the `capacity` parameter|| -|||Defined by the `capacity` parameter|Defined by the `maxCapacity` parameter| -||Defined by the `value` parameter|16 or `value`. , whichever is greater|| -||Defined by the `value` parameter|Defined by the `capacity` parameter or `value`. , whichever is greater.|| -||Defined by `value`. (`startIndex`, `length`)|Defined by the `capacity` parameter or `value`. , whichever is greater.|| - -The following example uses three of these constructor overloads to instantiate objects. - -:::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/instantiate1.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/instantiate1.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/instantiate1.vb" id="Snippet6"::: - -## Call StringBuilder methods - -Most of the methods that modify the string in a instance return a reference to that same instance. This enables you to call methods in two ways: - -- You can make individual method calls and ignore the return value, as the following example does. - - :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/call1.cs" id="Snippet4"::: - :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/call1.fs" id="Snippet4"::: - :::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/call1.vb" id="Snippet4"::: - -- You can make a series of method calls in a single statement. This can be convenient if you want to write a single statement that chains successive operations. The following example consolidates three method calls from the previous example into a single line of code. - - :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/call2.cs" id="Snippet5"::: - :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/call2.fs" id="Snippet5"::: - :::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/call2.vb" id="Snippet5"::: - -## Perform StringBuilder operations - -You can use the methods of the class to iterate, add, delete, or modify characters in a object. - -### Iterate StringBuilder characters - -You can access the characters in a object by using the property. In C#, is an indexer; in Visual Basic, it is the default property of the class. This enables you to set or retrieve individual characters by using their index only, without explicitly referencing the property. Characters in a object begin at index 0 (zero) and continue to index - 1. - -The following example illustrates the property. It appends ten random numbers to a object, and then iterates each character. If the character's Unicode category is , it decreases the number by 1 (or changes the number to 9 if its value is 0). The example displays the contents of the object both before and after the values of individual characters were changed. - -:::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/chars1.cs" id="Snippet7"::: -:::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/chars1.fs" id="Snippet7"::: -:::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/chars1.vb" id="Snippet7"::: - -[!INCLUDE[stringbuilder-performance-note](./includes/stringbuilder-perf-note.md)] - -### Add text to a StringBuilder object - -The class includes the following methods for expanding the contents of a object: - -- The method appends a string, a substring, a character array, a portion of a character array, a single character repeated multiple times, or the string representation of a primitive data type to a object. - -- The method appends a line terminator or a string along with a line terminator to a object. - -- The method appends a [composite format string](../../standard/base-types/composite-formatting.md) to a object. The string representations of objects included in the result string can reflect the formatting conventions of the current system culture or a specified culture. - -- The method inserts a string, a substring, multiple repetitions of a string, a character array, a portion of a character array, or the string representation of a primitive data type at a specified position in the object. The position is defined by a zero-based index. - -The following example uses the , , , and methods to expand the text of a object. - - :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/expand1.cs" id="Snippet9"::: - :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/expand1.fs" id="Snippet9"::: - :::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/expand1.vb" id="Snippet9"::: - -### Delete text from a StringBuilder object - -The class includes methods that can reduce the size of the current instance. The method removes all characters and sets the property to zero. The method deletes a specified number of characters starting at a particular index position. In addition, you can remove characters from the end of a object by setting its property to a value that is less than the length of the current instance. - -The following example removes some of the text from a object, displays its resulting capacity, maximum capacity, and length property values, and then calls the method to remove all the characters from the object. - -:::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/delete1.cs" id="Snippet10"::: -:::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/delete1.fs" id="Snippet10"::: -:::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/delete1.vb" id="Snippet10"::: - -### Modify the text in a StringBuilder object - -The method replaces all occurrences of a character or a string in the entire object or in a particular character range. The following example uses the method to replace all exclamation points (!) with question marks (?) in the object. - -:::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/replace1.cs" id="Snippet11"::: -:::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/replace1.fs" id="Snippet11"::: -:::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/replace1.vb" id="Snippet11"::: - -## Search the text in a StringBuilder object - -The class does not include methods similar to the , , and methods provided by the class, which allow you to search the object for a particular character or a substring. Determining the presence or starting character position of a substring requires that you search a value by using either a string search method or a regular expression method. There are four ways to implement such searches, as the following table shows. - -| Technique | Pros | Cons | -|-----------|------|------| -|Search string values before adding them to the object.|Useful for determining whether a substring exists.|Cannot be used when the index position of a substring is important.| -|Call and search the returned object.|Easy to use if you assign all the text to a object, and then begin to modify it.|Cumbersome to repeatedly call if you must make modifications before all text is added to the object.

You must remember to work from the end of the object's text if you're making changes.| -|Use the property to sequentially search a range of characters.|Useful if you're concerned with individual characters or a small substring.|Cumbersome if the number of characters to search is large or if the search logic is complex.

Results in very poor performance for objects that have grown very large through repeated method calls. | -|Convert the object to a object, and perform modifications on the object.|Useful if the number of modifications is small.|Negates the performance benefit of the class if the number of modifications is large.| - -Let's examine these techniques in greater detail. - -- If the goal of the search is to determine whether a particular substring exists (that is, if you aren't interested in the position of the substring), you can search strings before storing them in the object. The following example provides one possible implementation. It defines a `StringBuilderFinder` class whose constructor is passed a reference to a object and the substring to find in the string. In this case, the example tries to determine whether recorded temperatures are in Fahrenheit or Celsius, and adds the appropriate introductory text to the beginning of the object. A random number generator is used to select an array that contains data in either degrees Celsius or degrees Fahrenheit. - - :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/pattern1.cs" id="Snippet12"::: - :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/pattern1.fs" id="Snippet12"::: - :::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/pattern1.vb" id="Snippet12"::: - -- Call the method to convert the object to a object. You can search the string by using methods such as or , or you can use regular expressions and the class to search for patterns. Because both and objects use UTF-16 encoding to store characters, the index positions of characters, substrings, and regular expression matches are the same in both objects. This enables you to use methods to make changes at the same position at which that text is found in the object. - - > [!NOTE] - > If you adopt this approach, you should work from the end of the object to its beginning so that you don't have to repeatedly convert the object to a string. - - The following example illustrates this approach. It stores four occurrences of each letter of the English alphabet in a object. It then converts the text to a object and uses a regular expression to identify the starting position of each four-character sequence. Finally, it adds an underscore before each four-character sequence except for the first sequence, and converts the first character of the sequence to uppercase. - - :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/pattern2.cs" id="Snippet13"::: - :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/pattern2.fs" id="Snippet13"::: - :::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/pattern2.vb" id="Snippet13"::: - -- Use the property to sequentially search a range of characters in a object. This approach might not be practical if the number of characters to be searched is large or the search logic is particularly complex. For the performance implications of character-by-character index-based access for very large, chunked objects, see the documentation for the property. - - The following example is identical in functionality to the previous example but differs in implementation. It uses the property to detect when a character value has changed, inserts an underscore at that position, and converts the first character in the new sequence to uppercase. - - :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/pattern3.cs" id="Snippet14"::: - :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/pattern3.fs" id="Snippet14"::: - :::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/pattern3.vb" id="Snippet14"::: - -- Store all the unmodified text in the object, call the method to convert the object to a object, and perform the modifications on the object. You can use this approach if you have only a few modifications; otherwise, the cost of working with immutable strings might negate the performance benefits of using a object. - - The following example is identical in functionality to the previous two examples but differs in implementation. It creates a object, converts it to a object, and then uses a regular expression to perform all remaining modifications on the string. The method uses a lambda expression to perform the replacement on each match. - - :::code language="csharp" source="./snippets/System.Text/StringBuilder/Overview/csharp/pattern4.cs" id="Snippet15"::: - :::code language="fsharp" source="./snippets/System.Text/StringBuilder/Overview/fsharp/pattern4.fs" id="Snippet15"::: - :::code language="vb" source="./snippets/System.Text/StringBuilder/Overview/vb/pattern4.vb" id="Snippet15"::: - -## Convert the StringBuilder object to a string - -You must convert the object to a object before you can pass the string represented by the object to a method that has a parameter or display it in the user interface. You perform this conversion by calling the method. For an illustration, see the previous example, which calls the method to convert a object to a string so that it can be passed to a regular expression method. diff --git a/docs/fundamentals/runtime-libraries/system-threading-monitor-wait.md b/docs/fundamentals/runtime-libraries/system-threading-monitor-wait.md deleted file mode 100644 index b5e55df8dea7d..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-threading-monitor-wait.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: System.Threading.Monitor.Wait methods -description: Learn about the System.Threading.Monitor.Wait methods. -ms.date: 01/24/2024 ---- -# System.Threading.Monitor.Wait methods - -[!INCLUDE [context](includes/context.md)] - -## method - -This method does not return until it reacquires an exclusive lock on the `obj` parameter. - -The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations. - -The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the or method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the method again. - -When a thread calls `Wait`, it releases the lock and enters the waiting queue. At this point, the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked `Wait` remains in the waiting queue until either a thread that holds the lock invokes , or it is the next in the queue and a thread that holds the lock invokes . However, if `millisecondsTimeout` elapses before another thread invokes this object's or method, the original thread is moved to the ready queue in order to regain the lock. - -> [!NOTE] -> If is specified for the `millisecondsTimeout` parameter, this method blocks indefinitely unless the holder of the lock calls or . If `millisecondsTimeout` equals 0, the thread that calls `Wait` releases the lock and then immediately enters the ready queue in order to regain the lock. - -The caller executes `Wait` once, regardless of the number of times has been invoked for the specified object. Conceptually, the `Wait` method stores the number of times the caller invoked on the object and invokes as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls as many times as necessary to restore the saved count for the caller. Calling `Wait` releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released. - -> [!NOTE] -> A synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. - -The , , and `Wait` methods must be invoked from within a synchronized block of code. - -The remarks for the method explain what happens if is called when no threads are waiting. - -## method - -This method does not return until it reacquires an exclusive lock on the `obj` parameter. - -The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations. - -The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the or method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the method again. - -When a thread calls `Wait`, it releases the lock and enters the waiting queue. At this point, the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked `Wait` remains in the waiting queue until either a thread that holds the lock invokes , or it is the next in the queue and a thread that holds the lock invokes . However, if `timeout` milliseconds elapse before another thread invokes this object's or method, the original thread is moved to the ready queue in order to regain the lock. - -> [!NOTE] -> If a representing -1 millisecond is specified for the `timeout` parameter, this method blocks indefinitely unless the holder of the lock calls or . If `timeout` is 0 milliseconds, the thread that calls `Wait` releases the lock and then immediately enters the ready queue in order to regain the lock. - -The caller executes `Wait` once, regardless of the number of times has been invoked for the specified object. Conceptually, the `Wait` method stores the number of times the caller invoked on the object and invokes as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls as many times as necessary to restore the saved count for the caller. Calling `Wait` releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released. - -> [!NOTE] -> A synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state. - -The , , and `Wait` methods must be invoked from within a synchronized block of code. - -The remarks for the method explain what happens if is called when no threads are waiting. - -## Exit the context - -The`exitContext` parameter has no effect unless the method is called from inside a nondefault managed context. This can happen if your thread is inside a call to an instance of a class derived from . Even if you are currently executing a method on a class that is not derived from , like , you can be in a nondefault context if a is on your stack in the current application domain. - -When your code is executing in a nondefault context, specifying `true` for `exitContext` causes the thread to exit the nondefault managed context (that is, to transition to the default context) before executing the method. It returns to the original nondefault context after the call to the method completes. - -This can be useful when the context-bound class has the attribute applied. In that case, all calls to members of the class are automatically synchronized, and the synchronization domain is the entire body of code for the class. If code in the call stack of a member calls the method and specifies `true` for `exitContext`, the thread exits the synchronization domain, allowing a thread that is blocked on a call to any member of the object to proceed. When the method returns, the thread that made the call must wait to reenter the synchronization domain. diff --git a/docs/fundamentals/runtime-libraries/system-threading-monitor.md b/docs/fundamentals/runtime-libraries/system-threading-monitor.md deleted file mode 100644 index ade1e35bd1a57..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-threading-monitor.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: System.Threading.Monitor class -description: Learn about the System.Threading.Monitor class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Threading.Monitor class - -[!INCLUDE [context](includes/context.md)] - -The class allows you to synchronize access to a region of code by taking and releasing a lock on a particular object by calling the , , and methods. Object locks provide the ability to restrict access to a block of code, commonly called a critical section. While a thread owns the lock for an object, no other thread can acquire that lock. You can also use the class to ensure that no other thread is allowed to access a section of application code being executed by the lock owner, unless the other thread is executing the code using a different locked object. Because the Monitor class has thread affinity, the thread that acquired a lock must release the lock by calling the Monitor.Exit method. - -## Overview - - has the following features: - -- It is associated with an object on demand. -- It is unbound, which means it can be called directly from any context. -- An instance of the class cannot be created; the methods of the class are all static. Each method is passed the synchronized object that controls access to the critical section. - -> [!NOTE] -> Use the class to lock objects other than strings (that is, reference types other than ), not value types. For details, see the overloads of the method and [The lock object](#the-lock-object) section later in this article. - -The following table describes the actions that can be taken by threads that access synchronized objects: - -|Action|Description| -|------------|-----------------| -|, |Acquires a lock for an object. This action also marks the beginning of a critical section. No other thread can enter the critical section unless it is executing the instructions in the critical section using a different locked object.| -||Releases the lock on an object in order to permit other threads to lock and access the object. The calling thread waits while another thread accesses the object. Pulse signals are used to notify waiting threads about changes to an object's state.| -| (signal), |Sends a signal to one or more waiting threads. The signal notifies a waiting thread that the state of the locked object has changed, and the owner of the lock is ready to release the lock. The waiting thread is placed in the object's ready queue so that it might eventually receive the lock for the object. Once the thread has the lock, it can check the new state of the object to see if the required state has been reached.| -||Releases the lock on an object. This action also marks the end of a critical section protected by the locked object.| - -There are two sets of overloads for the and methods. One set of overloads has a `ref` (in C#) or `ByRef` (in Visual Basic) parameter that is atomically set to `true` if the lock is acquired, even if an exception is thrown when acquiring the lock. Use these overloads if it is critical to release the lock in all cases, even when the resources the lock is protecting might not be in a consistent state. - -## The lock object - -The Monitor class consists of `static` (`Shared` in Visual Basic) methods that operate on an object that controls access to the critical section. The following information is maintained for each synchronized object: - -- A reference to the thread that currently holds the lock. -- A reference to a ready queue, which contains the threads that are ready to obtain the lock. -- A reference to a waiting queue, which contains the threads that are waiting for notification of a change in the state of the locked object. - - locks objects (that is, reference types), not value types. While you can pass a value type to and , it is boxed separately for each call. Since each call creates a separate object, never blocks, and the code it is supposedly protecting is not really synchronized. In addition, the object passed to is different from the object passed to , so throws exception with the message "Object synchronization method was called from an unsynchronized block of code." - -The following example illustrates this problem. It launches ten tasks, each of which just sleeps for 250 milliseconds. Each task then updates a counter variable, `nTasks`, which is intended to count the number of tasks that actually launched and executed. Because `nTasks` is a global variable that can be updated by multiple tasks simultaneously, a monitor is used to protect it from simultaneous modification by multiple tasks. However, as the output from the example shows, each of the tasks throws a exception. - -:::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/badlock1.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/badlock1.vb" id="Snippet2"::: - -Each task throws a exception because the `nTasks` variable is boxed before the call to the method in each task. In other words, each method call is passed a separate variable that is independent of the others. `nTasks` is boxed again in the call to the method. Once again, this creates ten new boxed variables, which are independent of each other, `nTasks`, and the ten boxed variables created in the call to the method. The exception is thrown, then, because our code is attempting to release a lock on a newly created variable that was not previously locked. - -Although you can box a value type variable before calling and , as shown in the following example, and pass the same boxed object to both methods, there is no advantage to doing this. Changes to the unboxed variable are not reflected in the boxed copy, and there is no way to change the value of the boxed copy. - -:::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/badbox1.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/badbox1.vb" id="Snippet3"::: - -When selecting an object on which to synchronize, you should lock only on private or internal objects. Locking on external objects might result in deadlocks, because unrelated code could choose the same objects to lock on for different purposes. - -Note that you can synchronize on an object in multiple application domains if the object used for the lock derives from . - -## The critical section - -Use the and methods to mark the beginning and end of a critical section. - -> [!NOTE] -> The functionality provided by the and methods is identical to that provided by the [lock](/dotnet/csharp/language-reference/keywords/lock-statement) statement in C# and the [SyncLock](../../visual-basic/language-reference/statements/synclock-statement.md) statement in Visual Basic, except that the language constructs wrap the method overload and the method in a `try`…`finally` block to ensure that the monitor is released. - -If the critical section is a set of contiguous instructions, then the lock acquired by the method guarantees that only a single thread can execute the enclosed code with the locked object. In this case, we recommend that you place that code in a `try` block and place the call to the method in a `finally` block. This ensures that the lock is released even if an exception occurs. The following code fragment illustrates this pattern. - -:::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/Pattern2.cs" id="Snippet2"::: -:::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/Pattern2.vb" id="Snippet2"::: - -This facility is typically used to synchronize access to a static or instance method of a class. - -If a critical section spans an entire method, the locking facility can be achieved by placing the on the method, and specifying the value in the constructor of . When you use this attribute, the and method calls are not needed. The following code fragment illustrates this pattern: - -:::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/Pattern2.cs" id="Snippet3"::: -:::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/Pattern2.vb" id="Snippet3"::: - -Note that the attribute causes the current thread to hold the lock until the method returns; if the lock can be released sooner, use the class, the C# [lock](/dotnet/csharp/language-reference/keywords/lock-statement) statement, or the Visual Basic [SyncLock](../../visual-basic/language-reference/statements/synclock-statement.md) statement inside of the method instead of the attribute. - -While it is possible for the and statements that lock and release a given object to cross member or class boundaries or both, this practice is not recommended. - -## Pulse, PulseAll, and Wait - -Once a thread owns the lock and has entered the critical section that the lock protects, it can call the , , and methods. - -When the thread that holds the lock calls , the lock is released and the thread is added to the waiting queue of the synchronized object. The first thread in the ready queue, if any, acquires the lock and enters the critical section. The thread that called is moved from the waiting queue to the ready queue when either the or the method is called by the thread that holds the lock (to be moved, the thread must be at the head of the waiting queue). The method returns when the calling thread reacquires the lock. - -When the thread that holds the lock calls , the thread at the head of the waiting queue is moved to the ready queue. The call to the method moves all the threads from the waiting queue to the ready queue. - -## Monitors and wait handles - -It is important to note the distinction between the use of the class and objects. - -- The class is purely managed, fully portable, and might be more efficient in terms of operating-system resource requirements. -- objects represent operating-system waitable objects, are useful for synchronizing between managed and unmanaged code, and expose some advanced operating-system features like the ability to wait on many objects at once. - -## Examples - -The following example uses the class to synchronize access to a single instance of a random number generator represented by the class. The example creates ten tasks, each of which executes asynchronously on a thread pool thread. Each task generates 10,000 random numbers, calculates their average, and updates two procedure-level variables that maintain a running total of the number of random numbers generated and their sum. After all tasks have executed, these two values are then used to calculate the overall mean. - -:::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/example1.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/example1.vb" id="Snippet1"::: - -Because they can be accessed from any task running on a thread pool thread, access to the variables `total` and `n` must also be synchronized. The method is used for this purpose. - -The following example demonstrates the combined use of the class (implemented with the `lock` or `SyncLock` language construct), the class, and the class. It defines two `internal` (in C#) or `Friend` (in Visual Basic) classes, `SyncResource` and `UnSyncResource`, that respectively provide synchronized and unsynchronized access to a resource. To ensure that the example illustrates the difference between the synchronized and unsynchronized access (which could be the case if each method call completes rapidly), the method includes a random delay: for threads whose property is even, the method calls to introduce a delay of 2,000 milliseconds. Note that, because the `SyncResource` class is not public, none of the client code takes a lock on the synchronized resource; the internal class itself takes the lock. This prevents malicious code from taking a lock on a public object. - -:::code language="csharp" source="./snippets/System.Threading/Monitor/Overview/csharp/source.cs" id="Snippet1"::: -:::code language="vb" source="./snippets/System.Threading/Monitor/Overview/vb/source.vb" id="Snippet1"::: - -The example defines a variable, `numOps`, that defines the number of threads that will attempt to access the resource. The application thread calls the method for synchronized and unsynchronized access five times each. The method has a single parameter, a delegate that accepts no parameters and returns no value. For synchronized access, it invokes the `SyncUpdateResource` method; for unsynchronized access, it invokes the `UnSyncUpdateResource` method. After each set of method calls, the application thread calls the [AutoResetEvent.WaitOne](xref:System.Threading.WaitHandle.WaitOne*) method so that it blocks until the instance is signaled. - -Each call to the `SyncUpdateResource` method calls the internal `SyncResource.Access` method and then calls the method to decrement the `numOps` counter. The method Is used to decrement the counter, because otherwise you cannot be certain that a second thread will access the value before a first thread's decremented value has been stored in the variable. When the last synchronized worker thread decrements the counter to zero, indicating that all synchronized threads have completed accessing the resource, the `SyncUpdateResource` method calls the method, which signals the main thread to continue execution. - -Each call to the `UnSyncUpdateResource` method calls the internal `UnSyncResource.Access` method and then calls the method to decrement the `numOps` counter. Once again, the method Is used to decrement the counter to ensure that a second thread does not access the value before a first thread's decremented value has been assigned to the variable. When the last unsynchronized worker thread decrements the counter to zero, indicating that no more unsynchronized threads need to access the resource, the `UnSyncUpdateResource` method calls the method, which signals the main thread to continue execution. - -As the output from the example shows, synchronized access ensures that the calling thread exits the protected resource before another thread can access it; each thread waits on its predecessor. On the other hand, without the lock, the `UnSyncResource.Access` method is called in the order in which threads reach it. diff --git a/docs/fundamentals/runtime-libraries/system-threading-readerwriterlockslim.md b/docs/fundamentals/runtime-libraries/system-threading-readerwriterlockslim.md deleted file mode 100644 index 96a005f88deff..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-threading-readerwriterlockslim.md +++ /dev/null @@ -1,137 +0,0 @@ ---- -title: System.Threading.ReaderWriterLockSlim class -description: Learn about the System.Threading.ReaderWriterLockSlim class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Threading.ReaderWriterLockSlim class - -[!INCLUDE [context](includes/context.md)] - -Use to protect a resource that is read by multiple threads and written to by one thread at a time. allows multiple threads to be in read mode, allows one thread to be in write mode with exclusive ownership of the lock, and allows one thread that has read access to be in upgradeable read mode, from which the thread can upgrade to write mode without having to relinquish its read access to the resource. - -> [!NOTE] -> -> - is similar to , but it has simplified rules for recursion and for upgrading and downgrading lock state. avoids many cases of potential deadlock. In addition, the performance of is significantly better than . is recommended for all new development. -> - is not thread-abort safe. You should not use it in an environment where threads accessing it can be aborted, such as .NET Framework. If you're using .NET Core or .NET 5+, it should be fine. is not supported in .NET Core and [is obsolete](../../core/compatibility/core-libraries/5.0/thread-abort-obsolete.md) in .NET 5 and later versions. - -By default, new instances of are created with the flag and do not allow recursion. This default policy is recommended for all new development, because recursion introduces unnecessary complications and makes your code more prone to deadlocks. To simplify migration from existing projects that use or , you can use the flag to create instances of that allow recursion. - -A thread can enter the lock in three modes: read mode, write mode, and upgradeable read mode. (In the rest of this topic, "upgradeable read mode" is referred to as "upgradeable mode", and the phrase "enter `x` mode" is used in preference to the longer phrase "enter the lock in `x` mode".) - -Regardless of recursion policy, only one thread can be in write mode at any time. When a thread is in write mode, no other thread can enter the lock in any mode. Only one thread can be in upgradeable mode at any time. Any number of threads can be in read mode, and there can be one thread in upgradeable mode while other threads are in read mode. - -> [!IMPORTANT] -> This type implements the interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the interface topic. - - has managed thread affinity; that is, each object must make its own method calls to enter and exit lock modes. No thread can change the mode of another thread. - -If a does not allow recursion, a thread that tries to enter the lock can block for several reasons: - -- A thread that tries to enter read mode blocks if there are threads waiting to enter write mode or if there is a single thread in write mode. - - > [!NOTE] - > Blocking new readers when writers are queued is a lock fairness policy that favors writers. The current fairness policy balances fairness to readers and writers, to promote throughput in the most common scenarios. Future versions of .NET may introduce new fairness policies. - -- A thread that tries to enter upgradeable mode blocks if there is already a thread in upgradeable mode, if there are threads waiting to enter write mode, or if there is a single thread in write mode. - -- A thread that tries to enter write mode blocks if there is a thread in any of the three modes. - -## Upgrade and downgrade locks - -Upgradeable mode is intended for cases where a thread usually reads from the protected resource, but might need to write to it if some condition is met. A thread that has entered a in upgradeable mode has read access to the protected resource, and can upgrade to write mode by calling the or methods. Because there can be only one thread in upgradeable mode at a time, upgrading to write mode cannot deadlock when recursion is not allowed, which is the default policy. - -> [!IMPORTANT] -> Regardless of recursion policy, a thread that initially entered read mode is not allowed to upgrade to upgradeable mode or write mode, because that pattern creates a strong probability of deadlocks. For example, if two threads in read mode both try to enter write mode, they will deadlock. Upgradeable mode is designed to avoid such deadlocks. - -If there are other threads in read mode, the thread that is upgrading blocks. While the thread is blocked, other threads that try to enter read mode are blocked. When all threads have exited from read mode, the blocked upgradeable thread enters write mode. If there are other threads waiting to enter write mode, they remain blocked, because the single thread that is in upgradeable mode prevents them from gaining exclusive access to the resource. - -When the thread in upgradeable mode exits write mode, other threads that are waiting to enter read mode can do so, unless there are threads waiting to enter write mode. The thread in upgradeable mode can upgrade and downgrade indefinitely, as long as it is the only thread that writes to the protected resource. - -> [!IMPORTANT] -> If you allow multiple threads to enter write mode or upgradeable mode, you must not allow one thread to monopolize upgradeable mode. Otherwise, threads that try to enter write mode directly will be blocked indefinitely, and while they are blocked, other threads will be unable to enter read mode. - -A thread in upgradeable mode can downgrade to read mode by first calling the method and then calling the method. This downgrade pattern is allowed for all lock recursion policies, even . - -After downgrading to read mode, a thread cannot reenter upgradeable mode until it has exited from read mode. - -## Enter the lock recursively - -You can create a that supports recursive lock entry by using the constructor that specifies lock policy, and specifying . - -> [!NOTE] -> The use of recursion is not recommended for new development, because it introduces unnecessary complications and makes your code more prone to deadlocks. - -For a that allows recursion, the following can be said about the modes a thread can enter: - -- A thread in read mode can enter read mode recursively, but cannot enter write mode or upgradeable mode. If it tries to do this, a is thrown. Entering read mode and then entering write mode or upgradeable mode is a pattern with a strong probability of deadlocks, so it is not allowed. As discussed earlier, upgradeable mode is provided for cases where it is necessary to upgrade a lock. - -- A thread in upgradeable mode can enter write mode and/or read mode, and can enter any of the three modes recursively. However, an attempt to enter write mode blocks if there are other threads in read mode. - -- A thread in write mode can enter read mode and/or upgradeable mode, and can enter any of the three modes recursively. - -- A thread that has not entered the lock can enter any mode. This attempt can block for the same reasons as an attempt to enter a non-recursive lock. - -A thread can exit the modes it has entered in any order, as long as it exits each mode exactly as many times as it entered that mode. If a thread tries to exit a mode too many times, or to exit a mode it has not entered, a is thrown. - -## Lock states - -You may find it useful to think of the lock in terms of its states. A can be in one of four states: not entered, read, upgrade, and write. - -- Not entered: In this state, no threads have entered the lock (or all threads have exited the lock). - -- Read: In this state, one or more threads have entered the lock for read access to the protected resource. - - > [!NOTE] - > A thread can enter the lock in read mode by using the or methods, or by downgrading from upgradeable mode. - -- Upgrade: In this state, one thread has entered the lock for read access with the option to upgrade to write access (that is, in upgradeable mode), and zero or more threads have entered the lock for read access. No more than one thread at a time can enter the lock with the option to upgrade; additional threads that try to enter upgradeable mode are blocked. - -- Write: In this state, one thread has entered the lock for write access to the protected resource. That thread has exclusive possession of the lock. Any other thread that tries to enter the lock for any reason is blocked. - -The following table describes the transitions between lock states, for locks that do not allow recursion, when a thread `t` takes the action described in the leftmost column. At the time it takes the action, `t` has no mode. (The special case where `t` is in upgradeable mode is described in the table footnotes.) The top row describes the starting state of the lock. The cells describe what happens to the thread, and show changes to the lock state in parentheses. - -| Transition | Not entered (N) | Read (R) | Upgrade (U) | Write (W) | -|------------|-----------------|----------|-------------|-----------| -|`t` enters read mode|`t` enters (R).|`t` blocks if threads are waiting for write mode; otherwise, `t` enters.|`t` blocks if threads are waiting for write mode; otherwise, `t` enters.1|`t` blocks.| -|`t` enters upgradeable mode|`t` enters (U).|`t` blocks if threads are waiting for write mode or upgrade mode; otherwise, `t` enters (U).|`t` blocks.|`t` blocks.| -|`t` enters write mode|`t` enters (W).|`t` blocks.|`t` blocks.2|`t` blocks.| - -1 If `t` starts out in upgradeable mode, it enters read mode. This action never blocks. The lock state does not change. (The thread can then complete a downgrade to read mode by exiting upgradeable mode.) - -2 If `t` starts out in upgradeable mode, it blocks if there are threads in read mode. Otherwise it upgrades to write mode. The lock state changes to Write (W). If `t` blocks because there are threads in read mode, it enters write mode as soon as the last thread exits read mode, even if there are threads waiting to enter write mode. - -When a state change occurs because a thread exits the lock, the next thread to be awakened is selected as follows: - -- First, a thread that is waiting for write mode and is already in upgradeable mode (there can be at most one such thread). -- Failing that, a thread that is waiting for write mode. -- Failing that, a thread that is waiting for upgradeable mode. -- Failing that, all threads that are waiting for read mode. - -The subsequent state of the lock is always Write (W) in the first two cases and Upgrade (U) in the third case, regardless of the state of the lock when the exiting thread triggered the state change. In the last case, the state of the lock is Upgrade (U) if there is a thread in upgradeable mode after the state change, and Read (R) otherwise, regardless of the prior state. - -## Examples - -The following example shows a simple synchronized cache that holds strings with integer keys. An instance of is used to synchronize access to the that serves as the inner cache. - -The example includes simple methods to add to the cache, delete from the cache, and read from the cache. To demonstrate time-outs, the example includes a method that adds to the cache only if it can do so within a specified time-out. - -To demonstrate upgradeable mode, the example includes a method that retrieves the value associated with a key and compares it with a new value. If the value is unchanged, the method returns a status indicating no change. If no value is found for the key, the key/value pair is inserted. If the value has changed, it is updated. Upgradeable mode allows the thread to upgrade from read access to write access as needed, without the risk of deadlocks. - -The example includes a nested enumeration that specifies the return values for the method that demonstrates upgradeable mode. - -The example uses the parameterless constructor to create the lock, so recursion is not allowed. Programming the is simpler and less prone to error when the lock does not allow recursion. - -:::code language="csharp" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/csharp/classexample1.cs" id="Snippet11"::: -:::code language="vb" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/vb/classexample1.vb" id="Snippet11"::: -:::code language="csharp" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/csharp/classexample1.cs" id="Snippet12"::: -:::code language="vb" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/vb/classexample1.vb" id="Snippet12"::: - -The following code then uses the `SynchronizedCache` object to store a dictionary of vegetable names. It creates three tasks. The first writes the names of vegetables stored in an array to a `SynchronizedCache` instance. The second and third task display the names of the vegetables, the first in ascending order (from low index to high index), the second in descending order. The final task searches for the string "cucumber" and, when it finds it, calls the method to substitute the string "green bean". - -:::code language="csharp" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/csharp/classexample1.cs" id="Snippet11"::: -:::code language="vb" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/vb/classexample1.vb" id="Snippet11"::: -:::code language="csharp" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/csharp/classexample1.cs" id="Snippet13"::: -:::code language="vb" source="./snippets/System.Threading/ReaderWriterLockSlim/Overview/vb/classexample1.vb" id="Snippet13"::: diff --git a/docs/fundamentals/runtime-libraries/system-threading-tasks-task.md b/docs/fundamentals/runtime-libraries/system-threading-tasks-task.md deleted file mode 100644 index 3dd1a566012fd..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-threading-tasks-task.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: System.Threading.Tasks.Task class -description: Learn about the System.Threading.Tasks.Task class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - FSharp - - VB ---- -# System.Threading.Tasks.Task class - -[!INCLUDE [context](includes/context.md)] - -The class represents a single operation that does not return a value and that usually executes asynchronously. objects are one of the central components of the [task-based asynchronous pattern](../../standard/asynchronous-programming-patterns/task-based-asynchronous-pattern-tap.md) first introduced in .NET Framework 4. Because the work performed by a object typically executes asynchronously on a thread pool thread rather than synchronously on the main application thread, you can use the property, as well as the , , and properties, to determine the state of a task. Most commonly, a lambda expression is used to specify the work that the task is to perform. - -For operations that return values, you use the class. - -## Task instantiation - -The following example creates and executes four tasks. Three tasks execute an delegate named `action`, which accepts an argument of type . A fourth task executes a lambda expression (an delegate) that is defined inline in the call to the task creation method. Each task is instantiated and run in a different way: - -- Task `t1` is instantiated by calling a Task class constructor, but is started by calling its method only after task `t2` has started. - -- Task `t2` is instantiated and started in a single method call by calling the method. - -- Task `t3` is instantiated and started in a single method call by calling the method. - -- Task `t4` is executed synchronously on the main thread by calling the method. - -Because task `t4` executes synchronously, it executes on the main application thread. The remaining tasks execute asynchronously typically on one or more thread pool threads. - -:::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/startnew.cs" id="Snippet01"::: -:::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/startnew.fs" id="Snippet01"::: -:::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/startnew.vb" id="Snippet01"::: - -## Create and execute a task - -You can create instances in a variety of ways. The most common approach is to call the static method. The method provides a simple way to start a task using default values and without requiring additional parameters. The following example uses the method to start a task that loops and then displays the number of loop iterations: - -:::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/run1.cs" id="Snippet6"::: -:::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/run1.fs" id="Snippet6"::: -:::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/run1.vb" id="Snippet6"::: - -An alternative is the static method. The property returns a object. Overloads of the method let you specify parameters to pass to the task creation options and a task scheduler. The following example uses the method to start a task. It is functionally equivalent to the code in the previous example. - -:::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/startnew1.cs" id="Snippet7"::: -:::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/startnew1.fs" id="Snippet7"::: -:::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/startnew1.vb" id="Snippet7"::: - -For more complete examples, see [Task-based Asynchronous Programming](../../standard/parallel-programming/task-based-asynchronous-programming.md). - -## Separate task creation and execution - -The class also provides constructors that initialize the task but that do not schedule it for execution. For performance reasons, the or method is the preferred mechanism for creating and scheduling computational tasks, but for scenarios where creation and scheduling must be separated, you can use the constructors and then call the method to schedule the task for execution at a later time. - -## Wait for a task to complete - -Because tasks typically run asynchronously on a thread pool thread, the thread that creates and starts the task continues execution as soon as the task has been instantiated. In some cases, when the calling thread is the main application thread, the app may terminate before the task actually begins execution. In others, your application's logic may require that the calling thread continue execution only when one or more tasks have completed execution. You can synchronize the execution of the calling thread and the asynchronous tasks it launches by calling a `Wait` method to wait for one or more tasks to complete. - -To wait for a single task to complete, you can call its method. A call to the method blocks the calling thread until the single class instance has completed execution. - -The following example calls the parameterless method to wait unconditionally until a task completes. The task simulates work by calling the method to sleep for two seconds. - -:::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/Wait1.cs" id="Snippet8"::: -:::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/Wait1.fs" id="Snippet8"::: -:::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/Wait1.vb" id="Snippet8"::: - -You can also conditionally wait for a task to complete. The and methods block the calling thread until the task finishes or a timeout interval elapses, whichever comes first. Since the following example launches a task that sleeps for two seconds but defines a one-second timeout value, the calling thread blocks until the timeout expires and before the task has completed execution. - -:::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/Wait2.cs" id="Snippet9"::: -:::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/Wait2.fs" id="Snippet9"::: -:::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/Wait2.vb" id="Snippet9"::: - -You can also supply a cancellation token by calling the and methods. If the token's property is `true` or becomes `true` while the method is executing, the method throws an . - -In some cases, you may want to wait for the first of a series of executing tasks to complete, but don't care which task it is. For this purpose, you can call one of the overloads of the method. The following example creates three tasks, each of which sleeps for an interval determined by a random number generator. The method waits for the first task to complete. The example then displays information about the status of all three tasks. - -:::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/WhenAny1.cs" id="Snippet10"::: -:::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/WhenAny1.fs" id="Snippet10"::: -:::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/WaitAny1.vb" id="Snippet10"::: - -You can also wait for all of a series of tasks to complete by calling the method. The following example creates ten tasks, waits for all ten to complete, and then displays their status. - -:::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll1.cs" id="Snippet11"::: -:::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/WaitAll1.fs" id="Snippet11"::: -:::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/WaitAll1.vb" id="Snippet11"::: - -Note that when you wait for one or more tasks to complete, any exceptions thrown in the running tasks are propagated on the thread that calls the `Wait` method, as the following example shows. It launches 12 tasks, three of which complete normally and three of which throw an exception. Of the remaining six tasks, three are cancelled before they start, and three are cancelled while they are executing. Exceptions are thrown in the method call and are handled by a `try`/`catch` block. - -:::code language="csharp" source="./snippets/System.Threading.Tasks/Task/Overview/csharp/WaitAll2.cs" id="Snippet12"::: -:::code language="fsharp" source="./snippets/System.Threading.Tasks/Task/Overview/fsharp/WaitAll2.fs" id="Snippet12"::: -:::code language="vb" source="./snippets/System.Threading.Tasks/Task/Overview/vb/WaitAll2.vb" id="Snippet12"::: - -For more information on exception handling in task-based asynchronous operations, see [Exception Handling](../../standard/parallel-programming/exception-handling-task-parallel-library.md). - -## Tasks and culture - -Starting with desktop apps that target .NET Framework 4.6, the culture of the thread that creates and invokes a task becomes part of the thread's context. That is, regardless of the current culture of the thread on which the task executes, the current culture of the task is the culture of the calling thread. For apps that target versions of .NET Framework prior to .NET Framework 4.6, the culture of the task is the culture of the thread on which the task executes. For more information, see the "Culture and task-based asynchronous operations" section in the topic. - -> [!NOTE] -> Store apps follow the Windows Runtime in setting and getting the default culture. - -## For debugger developers - -For developers implementing custom debuggers, several internal and private members of task may be useful (these may change from release to release). The `m_taskId` field serves as the backing store for the property, however accessing this field directly from a debugger may be more efficient than accessing the same value through the property's getter method (the `s_taskIdCounter` counter is used to retrieve the next available ID for a task). Similarly, the `m_stateFlags` field stores information about the current lifecycle stage of the task, information also accessible through the property. The `m_action` field stores a reference to the task's delegate, and the `m_stateObject` field stores the async state passed to the task by the developer. Finally, for debuggers that parse stack frames, the `InternalWait` method serves a potential marker for when a task is entering a wait operation. diff --git a/docs/fundamentals/runtime-libraries/system-threading-tasks-taskscheduler.md b/docs/fundamentals/runtime-libraries/system-threading-tasks-taskscheduler.md deleted file mode 100644 index 8eb7d70b8678f..0000000000000 --- a/docs/fundamentals/runtime-libraries/system-threading-tasks-taskscheduler.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: System.Threading.Tasks.TaskScheduler class -description: Learn about the System.Threading.Tasks.TaskScheduler class. -ms.date: 12/31/2023 -dev_langs: - - CSharp - - VB ---- -# System.Threading.Tasks.TaskScheduler class - -[!INCLUDE [context](includes/context.md)] - -The class represents a task scheduler. A task scheduler ensures that the work of a task is eventually executed. - -The default task scheduler provides work-stealing for load-balancing, thread injection/retirement for maximum throughput, and overall good performance. It should be sufficient for most scenarios. - -The class also serves as the extension point for all customizable scheduling logic. This includes mechanisms such as how to schedule a task for execution, and how scheduled tasks should be exposed to debuggers. If you require special functionality, you can create a custom scheduler and enable it for specific tasks or queries. - -## The default task scheduler and the thread pool - -The default scheduler for the Task Parallel Library and PLINQ uses the .NET thread pool, which is represented by the class, to queue and execute work. The thread pool uses the information that is provided by the type to efficiently support the fine-grained parallelism (short-lived units of work) that parallel tasks and queries often represent. - -### The global queue vs. local queues - -The thread pool maintains a global FIFO (first-in, first-out) work queue for threads in each application domain. Whenever a program calls the (or ) method, the work is put on this shared queue and eventually de-queued onto the next thread that becomes available. Starting with .NET Framework 4, this queue uses a lock-free algorithm that resembles the class. By using this lock-free implementation, the thread pool spends less time when it queues and de-queues work items. This performance benefit is available to all programs that use the thread pool. - -Top-level tasks, which are tasks that are not created in the context of another task, are put on the global queue just like any other work item. However, nested or child tasks, which are created in the context of another task, are handled quite differently. A child or nested task is put on a local queue that is specific to the thread on which the parent task is executing. The parent task may be a top-level task or it also may be the child of another task. When this thread is ready for more work, it first looks in the local queue. If work items are waiting there, they can be accessed quickly. The local queues are accessed in last-in, first-out order (LIFO) to preserve cache locality and reduce contention. For more information about child tasks and nested tasks, see [Attached and Detached Child Tasks](../../standard/parallel-programming/attached-and-detached-child-tasks.md). - -The use of local queues not only reduces pressure on the global queue, but also takes advantage of data locality. Work items in the local queue frequently reference data structures that are physically near one another in memory. In these cases, the data is already in the cache after the first task has run and can be accessed quickly. Both [Parallel LINQ (PLINQ)](/dotnet/standard/parallel-programming/parallel-linq-plinq) and the class use nested tasks and child tasks extensively, and achieve significant speedups by using the local work queues. - -### Work stealing - -Starting with .NET Framework 4, the thread pool also features a work-stealing algorithm to help make sure that no threads are sitting idle while others still have work in their queues. When a thread-pool thread is ready for more work, it first looks at the head of its local queue, then in the global queue, and then in the local queues of other threads. If it finds a work item in the local queue of another thread, it first applies heuristics to make sure that it can run the work efficiently. If it can, it de-queues the work item from the tail (in FIFO order). This reduces contention on each local queue and preserves data locality. This architecture helps the thread pool load-balance work more efficiently than past versions did. - -### Long-running tasks - -You may want to explicitly prevent a task from being put on a local queue. For example, you may know that a particular work item will run for a relatively long time and is likely to block all other work items on the local queue. In this case, you can specify the option, which provides a hint to the scheduler that an additional thread might be required for the task so that it does not block the forward progress of other threads or work items on the local queue. By using this option you avoid the thread pool completely, including the global and local queues. - -### Task inlining - -In some cases when a is waited on, it may be executed synchronously on the thread that is performing the wait operation. This enhances performance by preventing the need for an additional thread and instead using the existing thread, which would have blocked otherwise. To prevent errors due to reentrancy, task inlining only occurs when the wait target is found in the relevant thread's local queue. - -## Specify a synchronization context - -You can use the method to specify that a task should be scheduled to run on a particular thread. This is useful in frameworks such as Windows Forms and Windows Presentation Foundation where access to user interface objects is often restricted to code that is running on the same thread on which the UI object was created. - -The following example uses the method in a Windows Presentation Foundation (WPF) app to schedule a task on the same thread that the user interface (UI) control was created on. The example creates a mosaic of images that are randomly selected from a specified directory. The WPF objects are used to load and resize the images. The raw pixels are then passed to a task that uses a loop to write the pixel data into a large single-byte array. No synchronization is required because no two tiles occupy the same array elements. The tiles can also be written in any order because their position is calculated independently of any other tile. The large array is then passed to a task that runs on the UI thread, where the pixel data is loaded into an Image control. - -The example moves data off the UI thread, modifies it by using parallel loops and objects, and then passes it back to a task that runs on the UI thread. This approach is useful when you have to use the Task Parallel Library to perform operations that either are not supported by the WPF API, or are not sufficiently fast. Another way to create an image mosaic in WPF is to use a control and add images to it. The handles the work of positioning the tiles. However, this work can only be performed on the UI thread. - -:::code language="csharp" source="./snippets/System.Threading.Tasks/TaskScheduler/FromCurrentSynchronizationContext/csharp/mainwindow.xaml.cs" id="Snippet01"::: -:::code language="vb" source="./snippets/System.Threading.Tasks/TaskScheduler/Overview/vb/MainWindow.xaml.vb" id="Snippet01"::: - -To create the example, create a WPF application project in Visual Studio and name it WPF_CS1 (for a C# WPF project) or WPF_VB1 (for a Visual Basic WPF project). Then do the following: - -1. In design view, drag an control from the **Toolbox** onto the upper left corner of the design surface. In the **Name** textbox of the **Properties** window, name the control "image". - -2. Drag a control from the **Toolbox** to the lower left part of the application window. In XAML view, specify the property of the button as "Make a mosaic", and specify its property as "100". Connect the event with the `button_Click` event handler defined in the example's code by adding `Click="button_Click"` to the `