I am asking the question regarding Immutable object pattern and implementing it. I am not talking about the existing classes in .Net library like String.
I understand that immutable objects are objects which once loaded cannot be modified by any external or internal component. What if I derive the immutable class as it is not a sealed class. Then assign the object to the base class, and call a method in the base class. I have effectively changed the state of the base immutable class as its state is that of the derived class object.
public class Person
{
private readonly string name;
public Person(string myName)
{
this.name = myName;
}
public string Name
{
get { return this.name; }
}
public void DisplayName()
{
Console.WriteLine(string.Format("Person's name is {0}", this.name));
}
}
public class AnotherPerson : Person
{
private string name1;
public AnotherPerson (string myName) : base(myName)
{
this.name1 = myName;
}
}
class Program
{
static void Main(string[] args)
{
Person me = new Prasanth("MyName");
me.DisplayName();
me = new AnotherPerson("AnotherName"); ;
me.DisplayName();
Console.ReadLine();
}
}
Output :
Person's name is MyName
Person's name is AnotherName
AnotherPerson
here, you've just reassigned a reference, the original object was not mutated. – Lucas TrzesniewskiDisplayName
property is not immutable, the string object that it originally pointed to is immutable – Mathias R. Jessen