# Description Remove stock phrasing and correct misleading or inconsistent technical documentation. The initial two passes covered 367 Markdown files, followed by an interactive review of 169 editorial flags. The U5 interpretation originally deferred in that review has since received the upstream Mantis answer recorded by #4843; remaining server/spec follow-ups stay explicit in the CTT log. - Correct package responsibilities, migration steps, API names, ownership, protocol descriptions and links. Keep bundled migration guides synchronized. Preserve historical conclusions as historical records with separate re-check notes. - Provide at least two rendered TOC levels throughout `docs/`. Convert appropriate architecture figures to Mermaid without changing code examples, transcripts or historical quotations. - Address the October 19 feedback with concrete setup/migration instructions, corrected certificate paths and PubSub names, shorter repeated caveats, consistent XML comments, and a full review of the Concepts guide. Retain #4839's API corrections. - Integrate #4841's runtime/performance guidance and review incoming/recent prose. Preserve dated measurements rather than claiming new benchmark runs; clarify allocation ratios, startup-only processor settings, JIT warm-up and the benchmark commit's scope. Missing raw measurement artifacts and repeat ranges remain tracked by #4842. - Merge master through `e8c5d800a` in `32c6394b7`. Resolve the CTT log conflict using the updated Mantis states and OPC answers, retaining historical framing and re-checks for C28/C32/C43. - Address the latest naming/index feedback in `adb5bf693`: rename the guides to `docs/WotCon.md` and `docs/WotNodeSetConversion.md`; move the provider and DataType-declaration contracts into the conversion guide and remove `docs/WoT.md`. Rename `samples/DI` to `samples/Di` and `samples/Isa95` to `samples/ISA95`. Add content-index READMEs to Di, FluentApi, ISA95, Lds and PubSub; update solution entries, project references, Docker/CI paths, test fixture paths and documentation links with exact casing. **WoT guide scope.** This branch retains the detailed conversion guide that #4758 had replaced with an anchor stub. Conversion limits, verified document sets, preservation rules and provider ownership now live together in `WotNodeSetConversion.md`; binding/runtime guidance remains in `WotBindings.md` and `WotCon.md`. The design-rationale/test-ledger prose was shortened, the oversized argument-table cell moved into its section, and existing anchors preserved. **SDK policy is a separate, explicit user-directed change.** `global.json` sets a stable minimum of `10.0.400`, `rollForward: latestMajor`, and `allowPrerelease: false`. Newer major SDKs are permitted; CI's explicit SDK pins are unchanged. README, GettingStarted, DeveloperGuide and Recycling instructions reflect the possible analyzer differences. The image-contract regression fix accepts compatible stable SDK images instead of requiring exact equality with the floor. The latest four rename/index threads are resolved after publication. Three older threads remain open: universal obsolete-removal timing, unconditional nonce-strength wording, and a blanket Vision NativeAOT claim. Existing implementation/evidence constraints are explained in their inline replies. The two-level TOCs remain as requested. ## Validation - `git diff --check` and staged diff checks: passed. The untouched upstream AutoID NodeSet retains its provenance bytes, including two existing license-header trailing spaces. - `.\.azurepipelines\validate-migration-plugin.ps1`: passed; 15 bundled migration documents and manifests synchronized. - Documentation/path validation: **101** documents retain two rendered TOC levels (**2,228** entries), with idempotent formatting. **52** new relative links and their anchors passed exact-case checks. No tracked references to the old guide/sample paths remain. Both relocated provider-contract sections are preserved in the destination. - `dotnet sln UA.slnx list`: passed; shows the renamed Di/ISA95 projects and the existing FluentApi/Lds/PubSub projects. Updated solution and pump ProjectReference paths also passed exact-case existence checks. - Latest focused commands, run from the repository root: ```powershell # Passed: 61 channel send-order and reconnect tests. dotnet test tests\Opc.Ua.Core.Tests\Opc.Ua.Core.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~UaSCBinaryChannelSendOrderTests|FullyQualifiedName~TcpReconnectKeyAgreementTests' --verbosity minimal # Passed: 5 pump datasheet tests; builds the renamed pump sample. dotnet test tests\Opc.Ua.Di.Tests\Opc.Ua.Di.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~PumpDatasheetConformanceTests' --verbosity minimal # Passed: 4 repository NodeSet path/round-trip tests, including the moved pump models. dotnet test tests\Opc.Ua.Types.Tests\Opc.Ua.Types.Tests.csproj -p:CustomTestTarget=net10.0 --filter 'FullyQualifiedName~RepositorySourceSurvivesSerializedLinkedPartitionsAsync' --verbosity minimal # Passed: build, zero warnings/errors. dotnet build samples\ISA95\MinimalIsa95Server\MinimalIsa95Server.csproj -p:CustomTestTarget=net10.0 -f net10.0 --verbosity minimal # Passed: dependent sample-test project build, zero warnings/errors. dotnet build tests\Opc.Ua.WotCon.Samples.Tests\Opc.Ua.WotCon.Samples.Tests.csproj -p:CustomTestTarget=net10.0 -f net10.0 --verbosity minimal ``` Earlier focused integration checks passed 2,620 tests across AutoID, event queues/scheduling, source generation, MCP/package profiles and WoT. Both reviewed Mermaid diagrams rendered locally without network access. These checks are not a full solution run. The full solution has **not** been rerun for this review. Earlier `dotnet test UA.slnx -p:CustomTestTarget=net10.0 --verbosity quiet` did not pass: three AOT projects rejected VSTest and 20 Vision tests failed during graphics initialization with `OutOfMemoryException`. Remaining long-running tests were stopped at the user's request. A focused Vision rerun passed 558 tests and reproduced those 20 failures. The earlier `dotnet test UA.slnx -p:CustomTestTarget=net48 --verbosity quiet` was blocked by the former SDK pin and was not retried after the policy change. The user approved proceeding with those limitations documented; current remote CI is not claimed green. ## Related Issues - Follow-up #4842 tracks the requested 2.0.2+ benchmark/tuning and diagnostic-tool documentation refresh. #4841 supplies documentation and earlier results, not all newly requested measurements. - #4758 explains the conversion guide's earlier consolidation; the current provider contracts are now consolidated into `WotNodeSetConversion.md`. - #4839 supplies the reviewed API corrections; #4843 supplies the updated CTT issue record. - The original prose cleanup and SDK policy were user-requested without a source issue. No new runtime architecture is introduced by these documentation edits. ## Checklist _Put an `x` in the boxes that apply. You can complete these step by step after opening the PR._ - [ ] I have signed the [CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf) and read the [CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md) doc. - [ ] I have added tests that prove my fix is effective or that my feature works and increased code coverage. - [x] I have added all necessary documentation. - [ ] I have verified that my changes do not introduce (new) build or analyzer warnings. - [ ] I ran **all** tests locally using the **UA.slnx** solution against at least .net **framework** and .net **10**, and all passed. - [ ] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. - [ ] I have addressed **all** PR feedback received. --------- Co-authored-by: Roman Ettlinger <romanett98@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
23 KiB
Source-Generated Data Types
The OPC UA .NET Standard stack includes a C# source generator that automatically
implements the IEncodeable interface for annotated POCO classes and enums. This
eliminates the need to hand-write Encode, Decode, IsEqual, and Clone
methods for custom OPC UA data types.
Contents
- Quick Start
- Prerequisites
- The
[DataType]Attribute - The
[DataTypeField]Attribute - Supported Property Types
- Class Variants
- Enum Support
- Registering Types with the Encodeable Factory
- Complete Example
StructureHandlingEnumDefaultValueHandlingEnum- Partial Init Properties
- Requirements and Constraints
- Generated File Output
- MSBuild Configuration
Quick Start
- Mark your class as
partialand decorate it with[DataType]. - Add public properties for each field — the generator does the rest.
using Opc.Ua;
namespace MyApp.Configuration
{
[DataType(Namespace = "urn:mycompany:myapp")]
public partial class DeviceConfiguration
{
public string Name { get; set; }
public int Port { get; set; }
public bool Enabled { get; set; }
}
}
The source generator will produce a partial class file that implements
IEncodeable, including:
TypeId,BinaryEncodingId,XmlEncodingIdpropertiesEncode(IEncoder)andDecode(IDecoder)methodsIsEqual(IEncodeable)for value comparisonClone()for deep copy- An activator class (e.g.
DeviceConfigurationActivator) for type registration
Prerequisites
Project Reference (internal development)
When developing within the OPC UA .NET Standard repository, reference the source generator project and import its props file:
<ItemGroup>
<ProjectReference
Include="..\..\tools\Opc.Ua.SourceGeneration\Opc.Ua.SourceGeneration.csproj">
<OutputItemType>Analyzer</OutputItemType>
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
</ProjectReference>
</ItemGroup>
<Import
Project="..\..\tools\Opc.Ua.SourceGeneration\OPCFoundation.Opc.Ua.SourceGeneration.props" />
NuGet Package (external consumers)
Add the OPCFoundation.NetStandard.Opc.Ua.SourceGeneration package:
dotnet add package OPCFoundation.NetStandard.Opc.Ua.SourceGeneration
The package is a development dependency, so the command adds a reference that runs the generator at build time and does not flow to consumers of your project:
<ItemGroup>
<PackageReference
Include="OPCFoundation.NetStandard.Opc.Ua.SourceGeneration"
Version="...">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
The [DataType] Attribute
Applied to a partial class, partial record class, or an enum to opt in
to source generation.
[AttributeUsage(
AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum)]
public sealed class DataTypeAttribute : Attribute
{
public string? Namespace { get; set; }
public string? DataTypeId { get; set; }
public string? BinaryEncodingId { get; set; }
public string? XmlEncodingId { get; set; }
}
Properties
| Property | Description |
|---|---|
Namespace |
The OPC UA namespace URI for this type. If omitted, falls back to [DataContract(Namespace=...)] if present, or urn:<dotnet.namespace.lowered>. |
DataTypeId |
Node ID string for the data type (e.g. "i=12345", "s=MyType", "g=<guid>"). Must be prefixed with i=, s=, g=, or b=. If omitted, defaults to a string identifier with the class name ("s=DeviceConfiguration"). |
BinaryEncodingId |
Optional binary encoding Node ID. Same prefix rules. |
XmlEncodingId |
Optional XML encoding Node ID. Same prefix rules. |
Namespace Resolution Order
The generator resolves the OPC UA namespace URI in this order:
[DataType(Namespace = "...")]— explicitly specified[DataContract(Namespace = "...")]— fromSystem.Runtime.Serializationurn:<dotnet.namespace.lowered>— automatic fallback (e.g.urn:myapp.configuration)
An explicit Namespace expression must be resolvable from the source compilation before generators run. Use a string literal or a const string declared in ordinary source or a referenced assembly. Do not reference a Namespaces constant emitted from a model file by the same generator run; generated symbols are not available while [DataType] attributes are analyzed. An unresolved explicit expression produces MODELGEN021 instead of silently falling back to a different namespace.
The [DataTypeField] Attribute
Applied to properties to control which fields participate in encoding and in what order.
[AttributeUsage(AttributeTargets.Property)]
public sealed class DataTypeFieldAttribute : Attribute
{
public int Order { get; set; }
public string? Name { get; set; }
public StructureHandling StructureHandling { get; set; }
public DefaultValueHandling DefaultValueHandling { get; set; }
public bool IsRequired { get; set; }
}
Properties
| Property | Description |
|---|---|
Order |
The encoding/decoding order of this field. Fields are sorted by Order before code generation. |
Name |
The serialized field name. Defaults to the property name if not set. |
StructureHandling |
For IEncodeable-typed fields: controls the encoding strategy. See StructureHandling. |
DefaultValueHandling |
Controls how default values are handled during encode/decode. See DefaultValueHandling. |
IsRequired |
Indicates whether the field is required. Reserved for future use with optional-field structures. |
Field Selection Rules
- If any property has
[DataTypeField]: only annotated properties are included in encoding. Non-annotated properties are excluded. - If no properties have
[DataTypeField]: all public read-write properties are automatically included, ordered by declaration position.
This lets you mix serialized and non-serialized properties in the same class:
[DataType(Namespace = "urn:myapp")]
public partial class ServerSettings
{
[DataTypeField(Order = 0)]
public string EndpointUrl { get; set; }
[DataTypeField(Order = 1, Name = "session_timeout")]
public uint SessionTimeout { get; set; }
// Not annotated — excluded from encoding
public string InternalNote { get; set; }
}
Supported Property Types
The source generator supports the following property types:
| C# Type | OPC UA Type | Encoder Method |
|---|---|---|
bool |
Boolean | WriteBoolean |
sbyte |
SByte | WriteSByte |
byte |
Byte | WriteByte |
short / Int16 |
Int16 | WriteInt16 |
ushort / UInt16 |
UInt16 | WriteUInt16 |
int / Int32 |
Int32 | WriteInt32 |
uint / UInt32 |
UInt32 | WriteUInt32 |
long / Int64 |
Int64 | WriteInt64 |
ulong / UInt64 |
UInt64 | WriteUInt64 |
float / Single |
Float | WriteFloat |
double / Double |
Double | WriteDouble |
string |
String | WriteString |
DateTime |
DateTime | WriteDateTime |
Guid / Uuid |
Guid | WriteGuid |
ByteString |
ByteString | WriteByteString |
NodeId |
NodeId | WriteNodeId |
ExpandedNodeId |
ExpandedNodeId | WriteExpandedNodeId |
StatusCode |
StatusCode | WriteStatusCode |
QualifiedName |
QualifiedName | WriteQualifiedName |
LocalizedText |
LocalizedText | WriteLocalizedText |
ExtensionObject |
ExtensionObject | WriteExtensionObject |
DataValue |
DataValue | WriteDataValue |
Variant |
Variant | WriteVariant |
DiagnosticInfo |
DiagnosticInfo | WriteDiagnosticInfo |
XmlElement |
XmlElement | WriteXmlElement |
Collections
ArrayOf<T>— use for arrays of any supported typeMatrixOf<T>— use for multi-dimensional arrays
Enums and IEncodeable Types
- Any C#
enumtype (encoded withWriteEnumerated/ReadEnumerated) - Any type implementing
IEncodeableor decorated with[DataType]
Unsupported Types
Properties with types not in the above list will produce:
- A warning if the property is not annotated with
[DataTypeField](the property is silently excluded) - An error if the property is annotated with
[DataTypeField](the type will not generate)
Class Variants
The generator handles several class shapes:
Regular Partial Class
[DataType(Namespace = "urn:myapp")]
public partial class MyConfig
{
public string Name { get; set; }
public int Value { get; set; }
}
Generates virtual methods for Encode, Decode, IsEqual, and Clone.
Sealed Partial Class
[DataType(Namespace = "urn:myapp")]
public sealed partial class MyConfig
{
public string Name { get; set; }
}
Generates non-virtual methods (no virtual or override keywords).
Record Class
[DataType(Namespace = Namespaces.OpcUaXsd)]
public partial record class BrowserOptions
{
[DataTypeField(Order = 0)]
public RequestHeader? RequestHeader { get; set; }
[DataTypeField(Order = 1)]
public uint MaxReferencesReturned { get; set; }
}
For record types, Clone() uses this with { } and IsEqual delegates to
the record's Equals implementation.
Derived Class (Inheritance)
When a [DataType] class derives from another IEncodeable base type, the
generator uses override instead of virtual and calls base.Encode()/
base.Decode() before encoding the derived fields. Clone() delegates to a
generated MemberwiseClone() that starts from a shallow copy of the whole
object — carrying the inherited fields — and then deep copies the derived
class's own reference-typed fields, the same shape the model-based generator
emits.
Internal Class
Classes declared as internal produce internal generated members.
Enum Support
Annotate an enum with [DataType] to register it as an OPC UA enumerated type:
[DataType(Namespace = "urn:myapp")]
public enum DeviceStatus
{
Unknown = 0,
Online = 1,
Offline = 2,
Error = 3
}
The generator produces an EnumeratedType<T> registration and an
EnumDefinition factory. The enum does not need to be partial.
Registering Types with the Encodeable Factory
The source generator creates an extension method to register all [DataType]
types in a namespace with an IEncodeableFactoryBuilder. The method is named
Add<NamespaceWithoutDots>DataTypes():
// Generated extension method name is derived from the .NET namespace:
// For namespace "MyApp.Configuration" → AddMyAppConfigurationDataTypes()
MessageContext.Factory.Builder
.AddMyAppConfigurationDataTypes()
.Commit();
For example, types in Opc.Ua.Gds.Server produce a method named
AddOpcUaGdsServerDataTypes():
protected override void OnServerStarting(
ApplicationConfiguration configuration)
{
base.OnServerStarting(configuration);
MessageContext.Factory.Builder
.AddOpcUaGdsServerDataTypes()
.Commit();
}
Complete Example
This example shows a node manager configuration type used in the MemoryBuffer quickstart server:
using Opc.Ua;
namespace MemoryBuffer
{
[DataType(Namespace = Namespaces.MemoryBuffer)]
public partial class MemoryBufferConfiguration
{
public MemoryBufferConfiguration()
{
}
[DataTypeField(Order = 1, StructureHandling = StructureHandling.Inline)]
public ArrayOf<MemoryBufferInstance> Buffers { get; set; }
}
[DataType(Namespace = Namespaces.MemoryBuffer)]
public partial class MemoryBufferInstance
{
public MemoryBufferInstance()
{
}
[DataTypeField(Order = 1)]
public string Name { get; set; }
[DataTypeField(Order = 2)]
public int TagCount { get; set; }
[DataTypeField(Order = 3)]
public string DataType { get; set; }
}
}
Key points in this example:
- Both classes are
partialand have parameterless constructors StructureHandling = StructureHandling.InlineonBuffersforces exact-type encoding (rather than extension object wrapping) since the element type is known at compile timeOrdercontrols the encoding sequence
StructureHandling Enum
When a property's type implements IEncodeable, the generator must choose
between two encoding strategies:
| Strategy | Method | Use When |
|---|---|---|
| Exact type | WriteEncodeable / ReadEncodeable |
The concrete type is always known (sealed, no subtypes) |
| Extension Object | WriteEncodeableAsExtensionObject / ReadEncodeableAsExtensionObject |
Subtypes may be substituted at runtime |
The StructureHandling enum controls this choice:
public enum StructureHandling
{
Auto = 0, // Generator decides based on type analysis
Inline = 1, // Force WriteEncodeable / ReadEncodeable
ExtensionObject = 2 // Force WriteEncodeableAsExtensionObject
}
| Value | Behavior |
|---|---|
Auto (default) |
If the field type is sealed and does not derive from another IEncodeable, WriteEncodeable is used. Otherwise, WriteEncodeableAsExtensionObject is used. |
Inline |
Forces WriteEncodeable/ReadEncodeable — the exact type is written inline. Use when the concrete type is always known at compile time. |
ExtensionObject |
Forces WriteEncodeableAsExtensionObject/ReadEncodeableAsExtensionObject — the value is wrapped in an ExtensionObject. Use when subtypes may be substituted at runtime. |
Example:
[DataType(Namespace = "urn:myapp")]
public partial class MyConfig
{
// Inline: always encodes as EndpointDescription directly
[DataTypeField(Order = 0, StructureHandling = StructureHandling.Inline)]
public EndpointDescription Endpoint { get; set; }
// Auto (default): generator decides based on whether the type is sealed
[DataTypeField(Order = 1)]
public OperationLimits Limits { get; set; }
}
DefaultValueHandling Enum
Controls how default values are handled during encode and decode. This is
particularly important for configuration types where constructor defaults
(e.g., NonceLength = 32, RejectSHA1SignedCertificates = true) should be
preserved when the field is absent from an XML configuration file.
[Flags]
public enum DefaultValueHandling
{
Exclude = 0, // Omit type defaults when safe; keep declared default for missing XML
Emit = 1, // Always write, even if default value
SetIfMissing = 2, // Always set on read, even if absent
Include = Emit | SetIfMissing // Always write AND read (legacy behavior)
}
OPC 10000-6 (5.3.5, 5.4.1, 5.4.2.1, 5.4.7) defines a missing field as the
default value of its type (Table 1: 0, false, null, ...), not a
per-field default. The generated code follows that rule for JSON and keeps a
declared-default leniency only for XML decoding:
| Value | Encode Behavior | Decode Behavior |
|---|---|---|
Exclude (default) |
The generated code omits a type-default value from XML/Compact JSON only when the declared default is known to be the type default, accounting for initializers and constructor assignments. Non-type-default or unknown declared defaults are always passed to the encoder. Binary and Verbose JSON always write. | JSON: a missing field is the type default. XML: a missing field keeps the declared (constructor/initializer) default, so configuration files that predate a field still load. Binary always reads. |
Emit |
Always writes the field, even if default. | Same as Exclude for decode. |
SetIfMissing |
Omits the field from XML/Compact JSON if its value is the type default. | A missing field is the type default in every encoding (overwrites the declared default). |
Include |
Always writes. | Always reads and assigns. |
Note that the Compact JsonEncoder drops a type-default value by itself even
when the generated code writes it; since a missing JSON field decodes to the
type default, e.g. int Port = 4840 set to 0 still round trips as 0.
The XmlEncoder never writes a null reference (string, ByteString, ...),
so a reference field with a non-null declared default that is set to null
reads back from XML as its declared default. Use SetIfMissing or Include
when that matters.
How It Works
The generated code uses two IEncoder/IDecoder APIs:
IEncoder.CanOmitFields: Returnstruefor XML and for the Compact JSON encoding,falsefor Binary and for the Verbose (and RawData) JSON encoding, which include all fields (OPC 10000-6 5.4.1). Used by the encode guard.IDecoder.HasField(string): Returnstrueif the field exists in the encoded data. Alwaystruefor Binary. Checks element/property existence for XML/JSON.
Generated encode (when Emit is NOT set and the declared default is the type
default, or SetIfMissing is set):
if (!encoder.CanOmitFields || Count != 0)
encoder.WriteInt32("Count", Count);
Generated decode (when SetIfMissing is NOT set):
if (decoder.EncodingType != EncodingType.Xml || decoder.HasField("NonceLength"))
NonceLength = decoder.ReadInt32("NonceLength");
Example: Configuration with Defaults
[DataType(Namespace = "urn:myapp")]
public partial class SecuritySettings
{
public SecuritySettings()
{
NonceLength = 32;
RejectExpiredCertificates = true;
}
// Exclude (default): always written (32 is not the type default);
// a field missing from XML keeps 32, a field missing from JSON is 0
[DataTypeField(Order = 0)]
public int NonceLength { get; set; } = 32;
// Exclude: constructor assignment prevents generated omission of false;
// missing XML keeps true, while missing JSON becomes false
[DataTypeField(Order = 1)]
public bool RejectExpiredCertificates { get; set; }
// Exclude (default): omit false from XML, preserve false when absent
[DataTypeField(Order = 2)]
public bool AllowAnonymous { get; set; }
}
Guideline:
Excludepreserves an explicitfalsefor the constructor-assigned Boolean shown here. A missing XML field keeps the constructor value; a missing JSON field becomes the type default. ChooseSetIfMissing(orIncludeto also always write the field) when an absent XML field should overwrite the constructor value with the type default, not merely because the constructor sets the property totrue.
Partial Init Properties
The source generator supports partial properties with init accessors for
immutable record types. This enables record classes with init-only properties
to participate in OPC UA binary and XML encoding — the generator creates a
private backing field for each such property and assigns to it directly during
Decode(), bypassing the init-only constraint.
Example
[DataType(Namespace = "urn:mycompany:myapp")]
public partial record class DeviceConfig
{
[DataTypeField(Order = 0)]
public partial string Name { get; init; } = "Default";
[DataTypeField(Order = 1)]
public partial int Port { get; init; }
}
The generator produces:
partial record class DeviceConfig : IEncodeable
{
private string __Name = "Default";
public partial string Name { get => __Name; init => __Name = value; }
private int __Port;
public partial int Port { get => __Port; init => __Port = value; }
public virtual void Decode(IDecoder decoder)
{
// Assigns to backing field, bypassing init constraint
if (decoder.HasField("Name")) __Name = decoder.ReadString("Name");
if (decoder.HasField("Port")) __Port = decoder.ReadInt32("Port");
}
// ...
}
How It Works
- For each property declared as
partialwith aninitaccessor, the generator emits a private backing field named__<PropertyName>. - The partial property implementation delegates
getandinitto that backing field. Decode()assigns to the backing field directly, which is legal because the field is a regular mutable field — only the publicinitaccessor is restricted to object-initializer contexts.Clone()for record types usesthis with { }, which copies init-only properties automatically via the copy constructor.
When to Use
- Use
partial+initproperties when you want an immutable public API (callers can only set values at construction time) while still allowing the decoder to populate the object from a binary or XML stream. - This is especially useful for configuration and options types modeled as
record class.
Requirements and Constraints
- Must be
partial: The class must be declaredpartialso the generator can extend it. Non-partial classes produce a compile error. - Parameterless constructor: The class must have a parameterless constructor (either explicit or implicit).
- Read-write properties: Only properties with both getter and setter are considered. Read-only properties are ignored.
- One
[DataType]per type:AllowMultiple = false— each type can have at most one[DataType]attribute. - Unique identifiers:
DataTypeIdmust be unique across all data types in the same namespace. For open namespaces, using a random GUID (g=<guid>) is recommended.
Generated File Output
The generator produces one .g.cs file per .NET namespace. The file name
follows the pattern <NamespaceWithoutDots>.Types.g.cs.
For example, types in Opc.Ua.Gds.Server produce a file named
OpcUaGdsServer.Types.g.cs containing:
- All partial class bodies (IEncodeable implementation)
- Activator classes for each type
- A single extension class with the
Add...DataTypes()registration method
MSBuild Configuration
The source generator supports the following MSBuild properties via the
OPCFoundation.Opc.Ua.SourceGeneration.props file:
| Property | Description |
|---|---|
ModelSourceGeneratorPublicDataTypeExtensions |
When true, the generated extension methods and their containing static class are public instead of internal. |