Skip to content

ConversionOperatorBuilder

Create explicit or implicit conversion operators.

See also: Emit Overview | TypeBuilder | OperatorBuilder


Factory Methods

Method Description
Explicit(targetType, sourceType, parameterName = "value") Create an explicit conversion operator
Implicit(targetType, sourceType, parameterName = "value") Create an implicit conversion operator

Body

// Expression body
op.WithExpressionBody("new MyType(value)")

// Block body
op.WithBody(body => body
    .AddStatement("var result = new MyType();")
    .AddStatement("result.Value = value;")
    .AddReturn("result"))

Conditional Compilation

op.When(Directives.Net7OrGreater)
op.InRegion("Conversions")

Attributes & XML Documentation

op.WithAttribute("Obsolete")
op.WithAttribute("Obsolete", a => a.WithArgument("\"Use other conversion\""))
op.WithXmlDoc("Converts from int to MyType.")
op.WithXmlDoc(doc => doc.Summary("Converts from int to MyType."))
op.AddUsing("System")

Example

// Standalone builder
var explicitConversion = ConversionOperatorBuilder.Explicit("UserId", "Guid")
    .WithExpressionBody("new UserId(value)")
    .WithXmlDoc("Creates a UserId from a Guid.");

typeBuilder.AddConversionOperator(explicitConversion)

// Convenience methods on TypeBuilder (recommended)
TypeBuilder.Struct("UserId")
    .AddExplicitConversion("Guid", op => op
        .WithExpressionBody("new UserId(value)"))
    .AddExplicitConversionTo("Guid", op => op
        .WithExpressionBody("value.Value"))
    .AddImplicitConversion("string", op => op
        .WithExpressionBody("new UserId(Guid.Parse(value))"))
    .AddImplicitConversionTo("string", op => op
        .WithExpressionBody("value.Value.ToString()"))

Properties

op.IsExplicit   // bool — true for explicit, false for implicit
op.TargetType   // string
op.SourceType   // string