Below is the code I have tried, is there a better way to do this?
In Protocol Buffers, we implement the builder pattern like this (vastly simplified):
public sealed class SomeMessage
{
public string Name { get; private set; }
public int Age { get; private set; }
// Can only be called in this class and nested types
private SomeMessage() {}
public sealed class Builder
{
private SomeMessage message = new SomeMessage();
public string Name
{
get { return message.Name; }
set { message.Name = value; }
}
public int Age
{
get { return message.Age; }
set { message.Age = value; }
}
public SomeMessage Build()
{
// Check for optional fields etc here
SomeMessage ret = message;
message = null; // Builder is invalid after this
return ret;
}
}
}
This isn't quite the same as the pattern in EJ2, but:
StringBuilder
does.Build()
to guarantee immutability. This unfortunately means it can't be used as a sort of "prototype" in the way that the EJ2 version can.this
for the sake of pre-C#3 users.I haven't really looked into inheritance with the builder pattern - it's not supported in Protocol Buffers anyway. I suspect it's quite tricky.