MethodBuilder¶
Create method declarations.
See also: Emit Overview | TypeBuilder | BodyBuilder
Factory Methods¶
| Method | Description |
|---|---|
For(string name) |
Create a method with the given name |
Parse(string signature) |
Parse from signature (e.g., "public async Task<int> GetCount()") |
Return Type¶
method.WithReturnType("void")
method.WithReturnType("string")
method.WithReturnType("Task<int>")
method.WithReturnType("IAsyncEnumerable<Order>")
Accessibility & Modifiers¶
method.WithAccessibility(Accessibility.Public)
method.WithAccessibility("public") // from snapshot or ValidSymbol.AccessibilityString
method.AsStatic()
method.AsVirtual()
method.AsOverride()
method.AsAbstract()
method.Async()
Explicit Interface Implementation¶
Generate methods with explicit interface syntax (IInterface.Method):
Explicit implementations automatically have no accessibility modifier.
Partial Methods Without Accessibility¶
Use Accessibility.NotApplicable for partial method declarations that should have no access modifier:
MethodBuilder
.Parse("partial void OnModelCreatingPartial(ModelBuilder modelBuilder)")
.WithAccessibility(Accessibility.NotApplicable)
// Produces: partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
This prevents the builder from emitting a default private modifier on the declaration.
Type Parameters¶
method.AddTypeParameter("T")
method.AddTypeParameter("T", tp => tp
.AsClass()
.WithNewConstraint())
method.AddTypeParameter(typeParameterBuilder)
Parameters¶
method.AddParameter("name", "string")
method.AddParameter("count", "int", p => p.WithDefaultValue("0"))
method.AddParameter(parameterBuilder)
Body¶
// Block body
method.WithBody(body => body
.AddStatement("Console.WriteLine(\"Starting\");")
.AddStatement("DoWork();")
.AddReturn("result"))
// Expression body
method.WithExpressionBody("_name")
// Append to expression body
method.AppendExpressionBody(".ToList()")
Attributes & XML Documentation¶
method.WithAttribute("HttpGet")
method.WithAttribute("Route", attr => attr.WithArgument("\"/api/items\""))
method.WithXmlDoc("Gets the customer name.")
method.WithXmlDoc(doc => doc
.Summary("Gets a customer by identifier.")
.Param("id", "The customer identifier.")
.Returns("The customer if found; otherwise, null."))