Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create a Read-Only Object Property in C#?

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,

like image 596
The Light Avatar asked Dec 17 '22 08:12

The Light


1 Answers

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.

like image 132
SLaks Avatar answered Jan 02 '23 00:01

SLaks