I have a read-only object but somewhere it's properties getting updated. Does C#
have anything to restrict that too from direct changes as well as via reflection?
Here is the POC code
class Program
{
static void Main(string[] args)
{
ReadOnlyCreator tester = new ReadOnlyCreator();
tester.ModifyTester();
Console.ReadLine();
}
}
class ClassUnderTest
{
public string SomeProp { get; set; }
}
class ReadOnlyCreator
{
private readonly ClassUnderTest _classUnderTest;
public ReadOnlyCreator()
{
_classUnderTest = new ClassUnderTest { SomeProp = "Init" };
}
public void ModifyTester()
{
Console.WriteLine("Before: " + _classUnderTest.SomeProp);
var modifier = new Modifier(_classUnderTest);
modifier.Modify();
Console.WriteLine("After: " + _classUnderTest.SomeProp);
}
}
class Modifier
{
private ClassUnderTest _classUnderTest;
public Modifier(ClassUnderTest classUnderTest)
{
_classUnderTest = classUnderTest;
}
public void Modify()
{
_classUnderTest.SomeProp = "Modified";
}