Skip to content

IndexerBuilder

Create indexer declarations (this[...]).

See also: Emit Overview | TypeBuilder | PropertyBuilder


Factory Methods

Method Description
For(string type) Create an indexer with the specified return type
For<T>(ValidSymbol<T> type) Create an indexer using a symbol's globally qualified name

Parameters

indexer.AddParameter("index", "int")
indexer.AddParameter("key", "string", p => p.WithAttribute("NotNull"))
indexer.AddParameter("name", validTypeSymbol)
indexer.AddParameter(preConfiguredParameter)

Accessors

// Expression-bodied getter
indexer.WithGetter("_items[index]")

// Block-bodied accessors
indexer.WithGetter(b => b.AddReturn("_items[index]"))
indexer.WithSetter(b => b.AddStatement("_items[index] = value"))

// Auto-implemented (get; set;)
indexer.WithAutoAccessors()

// Read-only
indexer.AsReadOnly()

// Init-only setter
indexer.WithInitOnlySetter()

Modifiers

indexer.WithAccessibility(Accessibility.Public)
indexer.WithAccessibility("public")  // from snapshot or ValidSymbol.AccessibilityString
indexer.AsVirtual()
indexer.AsOverride()
indexer.AsAbstract()
indexer.AsSealed()

Conditional Compilation

indexer.When(Directives.Net6OrGreater)
indexer.InRegion("Indexers")

Attributes & XML Documentation

indexer.WithAttribute("JsonIgnore")
indexer.WithAttribute("Obsolete", a => a.WithArgument("\"Use GetItem\""))
indexer.WithAttribute(preConfiguredAttribute)
indexer.WithXmlDoc("Gets or sets the element at the specified index.")
indexer.WithXmlDoc(doc => doc.Summary("Gets or sets the element."))
indexer.AddUsing("System.Text.Json.Serialization")

Example

var indexer = IndexerBuilder.For("T")
    .AddParameter("index", "int")
    .WithGetter("_items[index]")
    .WithSetter(b => b.AddStatement("_items[index] = value"))
    .WithXmlDoc("Gets or sets the element at the specified index.");

// Add to type
typeBuilder.AddIndexer(indexer)

Properties

indexer.Type  // string (return type)