Search code examples
c#referencereadonlydata-containers

readonly parameter with container Class (C#)


Ok so let's say that I have a data container class

public class DataContainer {
      public Person person;
}

and we already create an instance of this class

DataContainer dataContainer = new DataContainer();
dataContainer.Person = new Person("Smith");

and we try to pass it in a method that we want to be able to only read the container and not modified

public void ExampleMethod(in DataContainer dataContainer){
   dataConainer.Person.name = "blablabla" //we don't want to be able to do that
   dataContainer = new DataContainer(); // this is not possible because of in keyword
}

I tried the in keyword but it doesn't have any effect on prohibiting changes on container...

P.S. : convert the container into a struct is no solution because it will become immutable


Solution

  • If you don't want to be able to modify the Person.Name, then you could simply use encapsulation.

    I would design the Person class in the following way:

    class Person
    {
        public Person(string name)
        {
            Name = name;
        }
    
        public string Name { get; }
    }
    

    If this doesn't help, then the only other approach I see is to pass a DTO to ExampleMethod (which can be easily created using Automapper).

    var dto = _mapper.Map<DataContainerDto>(dataContainer);
    ExampleMethod(dto);
    
    ...
    
    public void ExampleMethod(DataContainerDto dataContainer)
    {
        // Nobody cares if I modify it,
        // because the original dataContainer reamains intact
        dataConainer.Person.name = "blablabla";
    }