ReadonlyCollection, are the objects immutable?

后端 未结 3 1015
隐瞒了意图╮
隐瞒了意图╮ 2021-01-19 01:44

I\'m trying using ReadOnlyCollection to make object immutable, I want the property of object are immutable.

public ReadOnlyCollection MyRea         


        
3条回答
  •  感情败类
    2021-01-19 02:10

    What is immutable is the collection itself, not the objects. For now, C# doesn't support immutable objects without wrapping them as ReadOnlyCollection does in your case.

    Well, you can still create immutable objects if their properties have no accessible setter. BTW, they're not immutable at all because they can mutate from a class member that may have equal or more accessibility than the setter.

    // Case 1
    public class A
    {
        public string Name { get; private set; }
    
        public void DoStuff() 
        {
            Name = "Whatever";
        }
    }
    
    // Case 2
    public class A
    {
        // This property will be settable unless the code accessing it
        // lives outside the assembly where A is contained...
        public string Name { get; internal set; }
    }
    
    // Case 3
    public class A
    {
        // This property will be settable in derived classes...
        public string Name { get; protected set; }
    }
    
    // Case 4: readonly fields is the nearest way to design an immutable object
    public class A
    {
         public readonly string Text = "Hello world";
    }
    

    As I said before, reference types are always mutable by definition and they can behave as immutable under certain conditions playing with member accessibility.

    Finally, structs are immutable but they're value types and they shouldn't be used just because they can represent immutable data. See this Q&A to learn more about why structs are immutable: Why are C# structs immutable?

提交回复
热议问题