• Avalanche.Core
Search Results for

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IContentAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • Dependency Injection
        • AccessorMessages
    • Avalanche.Binding
      • Introduction
    • Avalanche.Core
      • License
    • Avalanche.DataType
      • Introduction
      • DataType
        • IDataType
        • IListType
        • IMapType
        • IRecordType
        • IFieldType
        • IOneOfType
        • IAnyType
        • IStringType
        • IValueType
        • IIntegerType
        • IEnumerationType
        • IRealType
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • Enum
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystem
          • IFileSystemBrowse
          • IFileSystemCreateDirectory
          • IFileSystemDelete
          • IFileSystemFileAttribute
          • IFileSystemMount
          • IFileSystemMove
          • IFileSystemObserve
          • IFileSystemOpen
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Events
      • Utilities
        • Dispose
        • File Scanner
        • Visit Tree
        • File Operation
    • Avalanche.Identity
      • Introduction
      • Identity
      • IdentityParts
      • IdentityInterner
      • IdentityComparer
      • Print Tree
      • IdentityAccessors
        • Introduction
        • TypeName
    • Avalanche.Localization
      • Introduction
      • Localization
      • LocalizationFile
      • LocalizationFiles
      • LocalizationFileSystem
      • LocalizationFileFormat
      • LocalizationLine
      • LocalizationLines
      • TemplateFormat
      • CultureProvider
      • FallbackCultureProvider
      • ResourceManager
      • LocalizationError
      • Microsoft.Extensions
        • Introduction
        • DependencyInjection
        • FileProvider
        • Logging
        • ITextLocalizer
        • IFileLocalizer
        • Localization
      • Asp.Net
        • Introduction
        • Supplying localization
        • Inject to pages
        • Culture Assigned
        • Minimalistic Api
        • Diagnostics
      • Pluralization
        • Introduction
        • Multiple plural parameters
        • Custom PluralRules
        • Invariant Culture
        • Unit Prefix
        • IPluralRule
        • IPluralNumber
        • IPluralRules
        • CLDRs
        • Unicode.CLDR40
        • Unicode.CLDR41
        • Unicode.CLDR42
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Logging
        • Validation
    • Avalanche.Service
      • Introduction
      • Service
        • Introduction
        • IService
        • IServiceDisposable
        • IServiceDecoration
        • IServiceCast
        • IServiceObservable
        • IServiceContainer
        • Construction
        • Query
        • CancellationToken
        • CachePolicy
        • Scope
      • Handler
        • Introduction
        • IHandler
        • IHandlerCast
        • IHandlerDecoration
        • IHandlerWithOrder
        • CancellationToken
        • Cyclicity
        • Delegates
        • Invokable
        • ExportAttribute
        • OrderAttribute
        • PrintTree
        • Recursion
      • Query
        • Introduction
        • IQuery
        • IQueryCast
        • IQueryDecoration
      • Entry
        • Introduction
        • IEntry
        • IEntryCast
        • IEntryDecoration
        • IEntryObservable
        • IEntryVisitable
        • EntryState
      • Request
        • Introduction
        • IRequest
        • IRequestFor
        • IRequestToBeCached
        • IRequestToBeDisposed
        • RequestAttribute
        • ContextParameterAttribute
        • Print Tree
      • Dependency Injection
        • Introduction
        • Asp.Net
        • ServiceRequest<T>
        • Decorating a service
        • Handler
        • CachePolicy
        • CancellationToken
        • QueryLogger
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • ItfMessages
        • Win32Messages
        • ClrMessages
      • System
        • Introduction
        • AccessControlMessages
        • AggregateMessages
        • AppDomainMessages
        • ArgumentMessages
        • ArgumentNullMessages
        • ArgumentOutOfRangeMessages
        • ArithmeticMessages
        • ArrayMessages
        • AssemblyMessages
        • BadImageFormatMessages
        • CodeContractMessages
        • CodePageMessages
        • CollectionsMessages
        • CompilerServiceMessages
        • CryptographyMessages
        • CultureMessages
        • DiagnosticsMessages
        • EventSourceMessages
        • ExecutionEngineMessages
        • FormatMessages
        • HostProtectionMessages
        • IOMessages
        • IndexOutOfRangeMessages
        • InteropServiceMessages
        • InvalidCastMessages
        • InvalidOperationMessages
        • IsolatedStorageMessages
        • LazyMessages
        • MarshalerMessages
        • MemoryMessages
        • MiscellaneousMessages
        • NotImplementedMessages
        • NotSupportedMessages
        • ObjectDisposedMessages
        • OperationCanceledMessages
        • OverflowMessages
        • PlatformMessages
        • PolicyMessages
        • PrincipalMessages
        • ProgramMessages
        • ReferenceMessages
        • ReflectionMessages
        • RegionMessages
        • RemotingMessages
        • ResourcesMessages
        • SecurityMessages
        • SerializationMessages
        • StackMessages
        • TaskMessages
        • TextMessages
        • ThreadingMessages
        • TimeZoneMessages
        • TypeMessages
        • XmlMessages
      • HttpStatusCode
      • OpcUaStatusCode
    • Avalanche.Template
      • Introduction
      • TemplateFormats
      • ITemplatePrintable
      • ITemplateFormatPrintable
      • ITemplateText
      • ITemplateBreakdown
      • ITemplateFormat
      • ITemplateFormats
      • Extract Arguments
      • Emplacement
    • Avalanche.Tokenizer
      • Introduction
      • IToken
      • ITokenizer
      • Tokenizers
    • Avalanche.Utilities
      • Introduction
      • Collections
        • Tuples
        • StructList
        • ArrayList
        • BijectionMap
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • EnumerableExtensions
        • TupleUtilities
        • ArrayUtilities
      • Comparers
        • IGraphComparer
        • IGraphComparable
        • AlphaNumericComparer
        • EnumerableComparer
        • EnumerableGraphComparer
        • ReferenceComparer
        • KeyValuePairComparer
        • DefaultComparerProvider
        • RecordComparer
      • Cloners
        • ICloner
        • IGraphCloner
        • IGraphCloneable
        • ListCloner
        • DictionaryCloner
        • FieldCloner
        • PassthroughCloner
        • RecordCloner
        • ClonerProvider
      • Dispose
        • IDisposeAttachable
        • IDisposeBelatable
      • Provider
        • Introduction
        • ProviderBase
        • Delegate
        • Pipe
        • Cache
        • ResultCapture
        • AsReadOnly
        • AsService
        • IProviderEvent
      • Record
        • IRecordDescription
        • IFieldDescription
        • IConstructorDescription
        • IConstructionDescription
        • IParameterDescription
        • IRecordProviders
        • RecordDelegates
          • RecordCreate
          • RecordClone
          • RecordCopy
          • IRecordDelegates
        • FieldDelegates
          • FieldRead
          • FieldWrite
          • RecreateWith
          • IFieldDelegates
      • String
        • IEscaper
        • UnicodeString
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    Introduction

    IWriterBase is root interface for writers consumers.

    /// <summary>Root interface for writer sub-interfaces</summary>
    public interface IWriterBase
    {
        /// <summary>Try accept <paramref name="visitor"/>. Visits all <see cref="IWriterBase{From, To}"/> types that are implemented.</summary>
        /// <returns>Return true if all visitors were visited (all returned true).</returns>
        bool Accept(IWriterBaseVisitor visitor);
    }
    

    There are different ref versions of writer interface for different implementations.

    IWriterBase
    └── IWriterBase<From, To>
        ├── IWriter<From, To>
        ├── IWriterFromRef<From, To>
        ├── IWriterToRef<From, To>
        ├── IWriterFromRefToRef<From, To>
        ├── IWriter
        ├── IWriterFromRef
        ├── IWriterToRef
        └── IWriterFromRefToRef
    
    IWriterBase<From, To> describes writers read and write from specific 'From' type to 'To' type.
    /// <summary>Writes <typeparamref name="From"/> data to <typeparamref name="To"/>.</summary>
    /// <typeparam name="From">Value to write</typeparam>
    /// <typeparam name="To">Record/Container</typeparam>
    public interface IWriter<From, To> : IWriterT, IWriterBase<From, To>, IWriterTypes
    {
        /// <summary>Can write</summary>
        bool CanWrite { get; }
    
        /// <summary>Try write <paramref name="from"/> to container in <paramref name="to"/>.</summary>
        /// <param name="from">source where content is read from.</param>
        /// <param name="to">target where write is written to.</param>
        /// <returns>True if was write completed, false if write was not supported.</returns>
        /// <exception cref="Exception">Unexpected error.</exception>
        bool TryWrite(From from, To to, IServiceProvider? context = null);
    }
    
    /// <summary>Writes <typeparamref name="From"/> data to <typeparamref name="To"/>.</summary>
    /// <typeparam name="From">Value to write</typeparam>
    /// <typeparam name="To">Record/Container</typeparam>
    public interface IWriterFromRef<From, To> : IWriterBase<From, To>, IWriterTypes
    {
        /// <summary>Can write</summary>
        bool CanWrite { get; }
    
        /// <summary>Try write <paramref name="from"/> to container in <paramref name="to"/>.</summary>
        /// <param name="from">source where content is read from.</param>
        /// <param name="to">target where write is written to.</param>
        /// <returns>True if was write completed, false if write was not supported.</returns>
        /// <exception cref="Exception">Unexpected error.</exception>
        bool TryWrite(ref From from, To to, IServiceProvider? context = null);
    }
    
    /// <summary>Writes <typeparamref name="From"/> data to <typeparamref name="To"/>.</summary>
    /// <typeparam name="From">Value to write</typeparam>
    /// <typeparam name="To">Record/Container</typeparam>
    public interface IWriterToRef<From, To> : IWriterBase<From, To>, IWriterTypes
    {
        /// <summary>Can write</summary>
        bool CanWrite { get; }
    
        /// <summary>Try write <paramref name="from"/> to container in <paramref name="to"/> or create new container if not available.</summary>
        /// <param name="from">source where content is read from.</param>
        /// <param name="to">target where write is written to. If null then new container created if possible.</param>
        /// <returns>True if was write completed, false if write was not supported.</returns>
        /// <exception cref="Exception">Unexpected error.</exception>
        bool TryWrite(From from, ref To to, IServiceProvider? context = null);
    }
    
    /// <summary>Writes <typeparamref name="From"/> data to <typeparamref name="To"/>.</summary>
    /// <typeparam name="From">Value to write</typeparam>
    /// <typeparam name="To">Record/Container</typeparam>
    public interface IWriterFromRefToRef<From, To> : IWriterBase<From, To>, IWriterTypes
    {
        /// <summary>Can write</summary>
        bool CanWrite { get; }
    
        /// <summary>Try write <paramref name="from"/> to container in <paramref name="to"/> or create new container if not available.</summary>
        /// <param name="from">source where content is read from.</param>
        /// <param name="to">target where write is written to. If null then new container created if possible.</param>
        /// <returns>True if was write completed, false if write was not supported.</returns>
        /// <exception cref="Exception">Unexpected error.</exception>
        bool TryWrite(ref From from, ref To to, IServiceProvider? context = null);
    }
    
    IWriterBase generic method versions for generic writers.
    /// <summary>Accessor that can read from referable/struct type and write to referable type.</summary>
    public interface IWriter : IWriterGeneric
    {
        /// <summary>Can write</summary>
        bool CanWrite(Type from, Type to);
    
        /// <summary>Try write <paramref name="from"/> to container in <paramref name="to"/>.</summary>
        /// <param name="from">source where content is read from.</param>
        /// <param name="to">target where write is written to.</param>
        /// <returns>True if was write completed, false if write was not supported.</returns>
        /// <exception cref="Exception">Unexpected error.</exception>
        bool TryWrite<From, To>(From from, To to, IServiceProvider? context = null);
    }
    
    /// <summary>Accessor that can read from referred type and write to referable type.</summary>
    public interface IWriterFromRef : IWriterGeneric
    {
        /// <summary>Can write</summary>
        bool CanWrite(Type from, Type to);
    
        /// <summary>Try write <paramref name="from"/> to container in <paramref name="to"/>.</summary>
        /// <param name="from">source where content is read from.</param>
        /// <param name="to">target where write is written to.</param>
        /// <returns>True if was write completed, false if write was not supported.</returns>
        /// <exception cref="Exception">Unexpected error.</exception>
        bool TryWrite<From, To>(ref From from, To to, IServiceProvider? context = null);
    }
    
    /// <summary>Accessor that can read from referable/struct type and write to referred type.</summary>
    public interface IWriterToRef : IWriterGeneric
    {
        /// <summary>Can write</summary>
        bool CanWrite(Type from, Type to);
    
        /// <summary>Try write <paramref name="from"/> to container in <paramref name="to"/> or create new container if not available.</summary>
        /// <param name="from">source where content is read from.</param>
        /// <param name="to">target where write is written to. If null then new container created if possible.</param>
        /// <returns>True if was write completed, false if write was not supported.</returns>
        /// <exception cref="Exception">Unexpected error.</exception>
        bool TryWrite<From, To>(From from, ref To to, IServiceProvider? context = null);
    }
    
    /// <summary>Accessor that can read from referred type and write to referred type.</summary>
    public interface IWriterFromRefToRef : IWriterGeneric
    {
        /// <summary>Can write</summary>
        bool CanWrite(Type from, Type to);
    
        /// <summary>Try write <paramref name="from"/> to container in <paramref name="to"/> or create new container if not available.</summary>
        /// <param name="from">source where content is read from.</param>
        /// <param name="to">target where write is written to. If null then new container created if possible.</param>
        /// <returns>True if was write completed, false if write was not supported.</returns>
        /// <exception cref="Exception">Unexpected error.</exception>
        bool TryWrite<From, To>(ref From from, ref To to, IServiceProvider? context = null);
    }
    


    The consumer of writer can use IWriterBase and extension methods that forward to correct implementation.

    IWriterBase writer = new MyClassLabelWriter();
    writer.WriteAs("Hello", instance);
    

    IWriterBase<From, To> is another abstract interface for consumers.

    IWriterBase<string, MyClass> writer = new MyClassLabelWriter();
    writer.Write("Hello", instance);
    

    Writer

    Writer to class implements IWriter<From, To>.

    IWriter<string, MyClass> writer = new MyClassLabelWriter();
    

    Writer<From, To> base class can be used for implementations.

    public class MyClassLabelWriter : Writer<string, MyClass>
    {
        public override bool TryWrite(string from, MyClass to, IServiceProvider? context = null)
        {
            if (to == null) return false;
            to.Label = from;
            return true;
        }
    }
    

    Writer to struct implements IWriterToRef<From, To>.

    IWriterToRef<string, MyStruct> writer = new MyStructLabelWriter();
    
    public class MyStructLabelWriter : WriterToRef<string, MyStruct>
    {
        public override bool TryWrite(string from, ref MyStruct to, IServiceProvider? context = null)
        {
            to.Label = from;
            return true;
        }
    }
    

    Writer can be adapted from delegate.

    IWriter<string, MyClass> writer =
        DelegateWriter.Writer<string, MyClass>((string value, MyClass instance) => instance.Label = value);
    

    And for structs IWriterToRef<From, To>.

    IWriterToRef<string, MyStruct> writer =
        DelegateWriter.Writer<string, MyStruct>((string value, ref MyStruct instance) => instance.Label = value);
    

    Extension method .Write() forwards to .TryWrite() and throws StatusException with BadWriteNotSupported if return value is false.

    // Create instance
    MyClass instance = new MyClass { Label = "ABC" };
    // Write
    writer.Write("ZYX", instance);
    
    // Create instance
    MyStruct instance = new MyStruct { Label = "ABC" };
    // Write
    writer.Write("ZYX", ref instance);
    

    If writer is IWriterBase then extension method .WriteAs()<From, To> can be used to forward to .TryWrite().

    MyClass instance = new MyClass { Label = "ABC" };
    IWriterBase writer = new MyClassLabelWriter();
    writer.WriteAs<string, MyClass>("ZYX", instance);
    

    Reader

    Reader implements IWriterToRef<From, To> for class.

    IWriterToRef<MyClass, string> reader = new MyClassLabelReader();
    

    WriterToRef<From, To> base class can be used for convenient implementations.

    public class MyClassLabelReader : WriterToRef<MyClass, string>
    {
        public override bool TryWrite(MyClass from, ref string to, IServiceProvider? context = null)
        {
            if (from == null) return false;
            to = from.Label;
            return true;
        }
    }
    

    Reader can be adapted from delegate.

    IWriterToRef<MyClass, string> reader =
        DelegateWriter.Reader<MyClass, string>((MyClass @class) => @class.Label);
    

    Extension method .Write() can be used for reading, though pointer to output must be provided with ref.

    // Create instance
    MyClass instance = new MyClass { Label = "ABC" };
    // Write to here
    string label = null!;
    // Write from instance to stack frame
    reader.Write(instance, ref label);
    

    Extension method .Read() forwards to TryWrite().

    // Write from instance to stack frame
    label = reader.Read(instance);
    

    If writer is IWriterBase then extension method .ReadAs()<From, To> forwars to the correct .TryWrite.

    IWriterBase reader = new MyClassLabelReader();
    string label = reader.ReadAs<MyClass, string>(instance);
    

    Visitor

    IWriterVisitor is the interface for writer visitor implementations. Invoked from IWriterBase.Accept(IWriterVisitorBase).
    /// <summary>Root implementation for writer visitors: <see cref="IWriterVisitor"/>, <see cref="IRefererVisitor"/>.</summary>
    public interface IWriterBaseVisitor { }
    
    /// <summary>Writer visitor</summary>
    public interface IWriterVisitor : IWriterBaseVisitor
    {
        /// <summary>Try visit <paramref name="writerT"/>.</summary>
        /// <returns>true to continue visitation</returns>
        bool Visit<From, To>(IWriter<From, To> writerT);
        /// <summary>Try visit <paramref name="writerTFR"/>.</summary>
        /// <returns>true to continue visitation</returns>
        bool Visit<From, To>(IWriterFromRef<From, To> writerTFR);
        /// <summary>Try visit <paramref name="writerTTR"/>.</summary>
        /// <returns>true to continue visitation</returns>
        bool Visit<From, To>(IWriterToRef<From, To> writerTTR);
        /// <summary>Try visit <paramref name="writerTFRTR"/>.</summary>
        /// <returns>true to continue visitation</returns>
        bool Visit<From, To>(IWriterFromRefToRef<From, To> writerTFRTR);
    
        /// <summary>Try visit <paramref name="writer"/>.</summary>
        /// <returns>true to continue visitation</returns>
        bool Visit(IWriter writer);
        /// <summary>Try visit <paramref name="writerFR"/>.</summary>
        /// <returns>true to continue visitation</returns>
        bool Visit(IWriterFromRef writerFR);
        /// <summary>Try visit <paramref name="writerTR"/>.</summary>
        /// <returns>true to continue visitation</returns>
        bool Visit(IWriterToRef writerTR);
        /// <summary>Try visit <paramref name="writerFRTR"/>.</summary>
        /// <returns>true to continue visitation</returns>
        bool Visit(IWriterFromRefToRef writerFRTR);
    }
    


    Writer that implements IWriterBase accepts visitors.

    IWriterBase reader = new MyClassLabelReader();
    IWriterVisitor visitor = new MyVisitor();
    reader.Accept(visitor);
    
    public class MyVisitor : IWriterVisitor
    {
        public bool Visit<From, To>(IWriter<From, To> writerT)
        { WriteLine($"IWriter<{typeof(From).Name},{typeof(To).Name}>"); return true; }
        public bool Visit<From, To>(IWriterFromRef<From, To> writerTFR)
        { WriteLine($"IWriter<{typeof(From).Name},{typeof(To).Name}>"); return true; }
        public bool Visit<From, To>(IWriterToRef<From, To> writerTTR)
        { WriteLine($"IWriter<{typeof(From).Name},{typeof(To).Name}>"); return true; }
        public bool Visit<From, To>(IWriterFromRefToRef<From, To> writerTFRTR)
        { WriteLine($"IWriter<{typeof(From).Name},{typeof(To).Name}>"); return true; }
        public bool Visit(IWriter writer)
        { WriteLine($"IWriter"); return true; }
        public bool Visit(IWriterFromRef writerFR)
        { WriteLine($"IWriterFromRef"); return true; }
        public bool Visit(IWriterToRef writerTR)
        { WriteLine($"IWriterToRef"); return true; }
        public bool Visit(IWriterFromRefToRef writerFRTR)
        { WriteLine($"IWriterFromRefToRef"); return true; }
    }
    

    The extension method .GetWriterToAndFromTypes() gets implemented from and to types.

    List<KeyValuePair<Type, Type>> types = reader.GetWriterToAndFromTypes();
    

    As do .GetWriterInterfaces().

    List<Type> types = reader.GetWriterInterfaces();
    

    And .GetWriterRefAndTypes().

    List<(bool fromRef, Type fromType, bool toRef, Type toType)> types = reader.GetWriterRefAndTypes();
    

    IWriterComposition

    IWriterComposition interface exposes inner components for decorator implementations.
    /// <summary>Exposes writer internal components.</summary>
    public interface IWriterComposition : IWriterBase
    {
        /// <summary>Internal components.</summary>
        IWriterBase[]? Components { get; }
    }
    


    .PrintTree() extension method prints inner structure as tree.

    IWriterBase reader = new MyClassLabelReader();
    reader = WriterAdapter.Adapt(reader);
    string tree = reader.PrintTree();
    

    .VisitTree() extension method visits writer structure.

    IWriterBase reader = new MyClassLabelReader();
    reader = WriterAdapter.Adapt(reader);
    foreach (var line in reader.VisitTree())
        WriteLine(line);
    

    Full Example

    Full example
    using System;
    using System.Collections.Generic;
    using Avalanche.Service;
    using Avalanche.Writer;
    using static System.Console;
    
    public class writer
    {
        public static void Run()
        {
            {
                MyClass instance = new MyClass();
                // <01>
                IWriterBase writer = new MyClassLabelWriter();
                writer.WriteAs("Hello", instance);
                // </01>
            }
            {
                MyClass instance = new MyClass();
                // <02>
                IWriterBase<string, MyClass> writer = new MyClassLabelWriter();
                writer.Write("Hello", instance);
                // </02>
            }
    
            {
                // <W01>
                IWriter<string, MyClass> writer =
                    DelegateWriter.Writer<string, MyClass>((string value, MyClass instance) => instance.Label = value);
                // </W01>
            }
            {
                // <W01B>
                IWriterToRef<string, MyStruct> writer =
                    DelegateWriter.Writer<string, MyStruct>((string value, ref MyStruct instance) => instance.Label = value);
                // </W01B>
            }
            {
                // <W02>
                IWriter<string, MyClass> writer = new MyClassLabelWriter();
                // </W02>
            }
            {
                // <W02B>
                IWriterToRef<string, MyStruct> writer = new MyStructLabelWriter();
                // </W02B>
            }
            {
                IWriter<string, MyClass> writer = new MyClassLabelWriter();
                // <W04>
                // Create instance
                MyClass instance = new MyClass { Label = "ABC" };
                // Write
                writer.Write("ZYX", instance);
                // </W04>
            }
            {
                IWriterToRef<string, MyStruct> writer = new MyStructLabelWriter();
                // <W04B>
                // Create instance
                MyStruct instance = new MyStruct { Label = "ABC" };
                // Write
                writer.Write("ZYX", ref instance);
                // </W04B>
            }
            {
                // <W05>
                MyClass instance = new MyClass { Label = "ABC" };
                IWriterBase writer = new MyClassLabelWriter();
                writer.WriteAs<string, MyClass>("ZYX", instance);
                // </W05>
            }
    
            {
                // <R01>
                IWriterToRef<MyClass, string> reader =
                    DelegateWriter.Reader<MyClass, string>((MyClass @class) => @class.Label);
                // </R01>
            }
            {
                // <R02>
                IWriterToRef<MyClass, string> reader = new MyClassLabelReader();
                // </R02>
            }
            {
                IWriterToRef<MyClass, string> reader = new MyClassLabelReader();
                // <R04>
                // Create instance
                MyClass instance = new MyClass { Label = "ABC" };
                // Write to here
                string label = null!;
                // Write from instance to stack frame
                reader.Write(instance, ref label);
                // </R04>
                // <R05>
                // Write from instance to stack frame
                label = reader.Read(instance);
                // </R05>
            }
            {
                MyClass instance = new MyClass { Label = "ABC" };
                // <R06>
                IWriterBase reader = new MyClassLabelReader();
                string label = reader.ReadAs<MyClass, string>(instance);
                // </R06>
            }
    
            {
                // <V00>
                IWriterBase reader = new MyClassLabelReader();
                IWriterVisitor visitor = new MyVisitor();
                reader.Accept(visitor);
                // </V00>
            }
            {
                IWriterBase reader = new MyClassLabelReader();
                // <V01>
                List<KeyValuePair<Type, Type>> types = reader.GetWriterToAndFromTypes();
                // </V01>
            }
            {
                IWriterBase reader = new MyClassLabelReader();
                // <V02>
                List<Type> types = reader.GetWriterInterfaces();
                // </V02>
            }
            {
                IWriterBase reader = new MyClassLabelReader();
                // <V03>
                List<(bool fromRef, Type fromType, bool toRef, Type toType)> types = reader.GetWriterRefAndTypes();
                // </V03>
            }
            {
                // <C04>
                IWriterBase reader = new MyClassLabelReader();
                reader = WriterAdapter.Adapt(reader);
                string tree = reader.PrintTree();
                // </C04>
                WriteLine(tree);
            }
            {
                // <C05>
                IWriterBase reader = new MyClassLabelReader();
                reader = WriterAdapter.Adapt(reader);
                foreach (var line in reader.VisitTree())
                    WriteLine(line);
                // </C05>
            }
    
        }
    
        // <00>
        public class MyClass
        {
            public string Label = null!;
        }
        public struct MyStruct
        {
            public string Label;
        }
        // </00>
    
        // <R03>
        public class MyClassLabelReader : WriterToRef<MyClass, string>
        {
            public override bool TryWrite(MyClass from, ref string to, IServiceProvider? context = null)
            {
                if (from == null) return false;
                to = from.Label;
                return true;
            }
        }
        // </R03>
    
        // <W03>
        public class MyClassLabelWriter : Writer<string, MyClass>
        {
            public override bool TryWrite(string from, MyClass to, IServiceProvider? context = null)
            {
                if (to == null) return false;
                to.Label = from;
                return true;
            }
        }
        // </W03>
        // <W03B>
        public class MyStructLabelWriter : WriterToRef<string, MyStruct>
        {
            public override bool TryWrite(string from, ref MyStruct to, IServiceProvider? context = null)
            {
                to.Label = from;
                return true;
            }
        }
        // </W03B>
        // <V06>
        public class MyVisitor : IWriterVisitor
        {
            public bool Visit<From, To>(IWriter<From, To> writerT)
            { WriteLine($"IWriter<{typeof(From).Name},{typeof(To).Name}>"); return true; }
            public bool Visit<From, To>(IWriterFromRef<From, To> writerTFR)
            { WriteLine($"IWriter<{typeof(From).Name},{typeof(To).Name}>"); return true; }
            public bool Visit<From, To>(IWriterToRef<From, To> writerTTR)
            { WriteLine($"IWriter<{typeof(From).Name},{typeof(To).Name}>"); return true; }
            public bool Visit<From, To>(IWriterFromRefToRef<From, To> writerTFRTR)
            { WriteLine($"IWriter<{typeof(From).Name},{typeof(To).Name}>"); return true; }
            public bool Visit(IWriter writer)
            { WriteLine($"IWriter"); return true; }
            public bool Visit(IWriterFromRef writerFR)
            { WriteLine($"IWriterFromRef"); return true; }
            public bool Visit(IWriterToRef writerTR)
            { WriteLine($"IWriterToRef"); return true; }
            public bool Visit(IWriterFromRefToRef writerFRTR)
            { WriteLine($"IWriterFromRefToRef"); return true; }
        }
        // </V06>
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen