I’m working on implementing a builder pattern in C# after seeing it work great in Java. I found this pattern in a programming book and wanted to try it out in my project.
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("SUV Model").Brand("Toyota").Capacity(5).create();
}
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 create() {
return new Vehicle(this);
}
}
}
But when I try the same approach in 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 create()
{
return new Vehicle(this);
}
}
}
I get compiler errors saying I can’t declare instance members in a static class. What am I doing wrong here? Can this pattern work in C# the same way it does in Java? Also wondering if this approach is thread safe when multiple users access it.