Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Management - Readonly data

Tags:

c#

readonly

I'm working on a some project in C#, and I came across the following problem:

I have some data-type classes, for example a Person class, which keeps information about a person.

In addition, I have a DataManager class, which is responsible of managing the persons in my program. If you want to add, get, find, or remove a person, you would do it only through the DataManager class.

The problem is that I don't want anyone besides the DataManager class to be able to alter the Person objects. If someone calls DataManager.getPerson(int ID) for example, they would get a Person object and would be able to use the setter functions of that Person object to alter its contents (first name, last name, ID, etc.).

I want to avoid that. I want only the DataManager class to be able to alter the Person objects (through methods such as DataManager.changeFirstNameForPerson(int ID, string name)).

What is the best class structure that can achieve that?

like image 838
Malki Avatar asked May 25 '26 02:05

Malki


2 Answers

Well, you'll never be able to stop people from changing the values 100%. They could always just go through reflection.

But, from the API standpoint, you could make all the getters of your Person class public, adn all of the setters internal. As long as the Person and DataManager classes are in the same assembly, the DataManager will be able to access the setters fine, but other apps that reference the assembly cannot.

public class Person
{
    public string Fname { get; internal set; }
}


public class DataManager
{
    public void ChangeNameForPerson(int id, string fname)
    {
        Person p = Person.GetById(id);
        // Inside the same assembly.  Setter is accessible
        p.Fname = fname;
    }
}

Outside of the assembly, you'd have this:

Person p = DataManager.GetPerson(1);
p.Fname = "asdf"; // Compile time error
DataManager.ChangeNameForPerson(1, "asdf"); // Works fine
like image 129
Samuel Meacham Avatar answered May 27 '26 16:05

Samuel Meacham


The first two things that spring to mind would be:

1 - Make the Person property setters protected and have DataManager derive from Person

2 - Make the Person property setters internal and put Person and DataManager in their own assembly

like image 32
heisenberg Avatar answered May 27 '26 16:05

heisenberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!