I’ve been working through Effective Java by Josh Bloch and came across his builder pattern implementation. The pattern works great in Java but I’m running into issues when trying to convert it to C#. Here’s my working Java version:
public class Vehicle {
private String model;
private String brand;
private int capacity = 0;
public static void main(String[] args) {
Vehicle newVehicle = new Vehicle.Creator("Test Model").Brand("Test Brand").Capacity(5).construct();
}
private Vehicle(Creator creator) {
this.model = creator.model;
this.brand = creator.brand;
this.capacity = creator.capacity;
}
public static class Creator {
private String model;
private String brand;
private int capacity = 0;
public Creator(String model) {
this.model = model;
}
public Creator Brand(String brand) {
this.brand = brand;
return this;
}
public Creator Capacity(int capacity) {
this.capacity = capacity;
return this;
}
public Vehicle construct() {
return new Vehicle(this);
}
}
}
When I try to port this to C#:
public class Vehicle
{
private String model;
private String brand;
private Vehicle(Creator creator)
{
model = creator.model;
brand = creator.brand;
}
public static class Creator
{
private String model;
private String brand;
private int capacity = 0;
public Creator(String val)
{
this.model = val;
}
public Creator Brand(String val)
{
this.brand = val;
return this;
}
public Creator Capacity(int val)
{
this.capacity = val;
return this;
}
public Vehicle construct()
{
return new Vehicle(this);
}
}
}
I get compiler errors saying “cannot declare instance members in a static class”. What am I missing here? Can this builder approach work in C# the same way it does in Java? Also wondering about thread safety with this approach.