e.g.: say I have a class "Car", with only public getters (which don't have any side effects):
public enum CarType
{
Hatch,
SUV,
}
public class Car
{
public Car(CarType carType, string model, bool isElectric)
{
CarType = carType;
Model = model;
IsElectric = isElectric;
}
public CarType CarType { get; private set; }
public string Model { get; private set; }
public bool IsElectric { get; private set; }
}
Now a static instance of the Car class is created in some other C# class, like this:
protected static readonly Car _defaultCar = new Car(CarType.SUV, "123", true);
Is it safe to use _defaultCar from multiple threads ?
CodePudding user response:
If the object is immutable, it is perfectly safe to access from multiple threads. This is true in general, regardless if the object is static or not. Private setters are not sufficient in it self, since there could be methods that mutate the properties.
Note that you should remove the private setter for immutable objects, creating get-only properties. That better signals that the type is immutable. In some cases you can also use a readonly struct to guarantee immutability.
Also keep in mind what objects you expose. Bool, string, and enums are all immutable, but if you exposed say a list, you risk the list being mutated, and lists are not thread safe.