As can be seen below, the user is able to change the readonly product field/property:
class Program
{
static void Main(string[] args)
{
var product = Product.Create("Orange");
var order = Order.Create(product);
order.Product.Name = "Banana"; // Main method shouldn't be able to change any property of product!
}
}
public class Order
{
public Order(Product product)
{
this.Product = product;
}
public readonly Product Product;
public static Order Create(Product product)
{
return new Order (product);
}
}
public class Product
{
private Product(){}
public string Name { get; set; }
public static Product Create(string name)
{
return new Product { Name = name };
}
}
I thought it's quite basic but it doesn't seem so.
How to Create a Read-Only Object Property or Field in C#?!
Thanks,
The readonly
keyword prevents you from putting a new instance into the field.
It doesn't magically make any object inside the field immutable.
What do you expect to happen if you write
readonly Product x = Product.Create();
Product y;
y = x;
y.Name = "Changed!";
If you want an immutable object, you need to make the class itself immutable by removing all public setters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With