What does immutable and readonly mean in C#?

前端 未结 8 982
我寻月下人不归
我寻月下人不归 2021-02-13 09:44

Is it correct that it is not possible to change the value of an immutable object?

I have two scenarios regarding readonly that I want to understand:

8条回答
  •  清歌不尽
    2021-02-13 10:13

    In languages like C++ there are quite a few different uses of the keyword "const", it is partly easy for developers to pass constant parameters and also constant pointers of constant values.

    That is not easy in C#. We need to build immutable class by definition, which means Once an instance is created, there is no way it can be changed programmatically.

    Java has a little easier way than C# because of the keyword final and its usages.

    Lets consider this example and see how immutable it is..

    public sealed class ImmutableFoo
        {
            private ImmutableFoo()
            {
    
            }
    
            public string SomeValue { get; private set; }
            //more properties go here
    
            public sealed class Builder
            {
                private readonly ImmutableFoo _instanceFoo = new ImmutableFoo();
                public Builder SetSomeValue(string someValue)
                {
                    _instanceFoo.SomeValue = someValue;
                    return this;
                }
    
                /// Set more properties go here
                /// 
    
                public ImmutableFoo Build()
                {
                    return _instanceFoo;
                }
            }
        }
    

    You can use it like this

    public class Program
        {
            public static void Main(string[] args)
            {
                ImmutableFoo foo = new ImmutableFoo.Builder()
                    .SetSomeValue("Assil is my name")
                    .Build();
    
                Console.WriteLine(foo.SomeValue);
                Console.WriteLine("Hit enter to terminate");
                Console.ReadLine();
            }
        }
    

提交回复
热议问题