[Proposal]: Factory methods
Factory methods
Specification: proposals/factory-methods.md Discussion: https://github.com/dotnet/csharplang/discussions/6602
Summary
This proposal will extend the scenarios in which object initializers can be used to include type factory methods in addition to constructors.
Motivation
Records need to support initializer style expressions in scenarios other than
standard object construction to support with expressions. This though is
simply adding a special property to a specific named method in a type. Records
though are not alone in wanting to denote methods as being used exclusively for
construction. Factory methods serve the same purpose in .NET and are common
throughout our framework.
The ability to mark methods as being used exclusively for creation should
become a standalone feature. Developers will be able to mark members which
exist soley to create objects with [Factory] and the language will
give such methods the same flexibility as object constructors. That means
those methods can now be used in combination with object and collection
initializers.
public class Widget
{
public string Name { get; set; }
public int Id { get; init; }
internal Widget() { }
}
public static class WidgetFactory
{
[Factory]
public static Widget Create() => new Widget();
}
var w = WidgetFactory.Create()
{
Name = "JaredPar",
Id = 42;
}Design meetings
Source: dotnet/csharplang