I had a class with 6 properties which were basically 3 pairs of properties, each pair containing data about one thing. All of these properties were public, but setting them was protected. It is shown in the code below:
public class MyClass
{
public Data1Type Item1Data1 { get; protected set; }
public Data2Type Item1Data2 { get; protected set; }
public Data1Type Item2Data1 { get; protected set; }
public Data2Type Item2Data2 { get; protected set; }
public Data1Type Item3Data1 { get; protected set; }
public Data2Type Item3Data2 { get; protected set; }
}
Because each pair of properties was basically treated as one item, I decided to make a struct which looks like this:
struct Item
{
Data1Type Data1;
Data2Type Data2;
}
So I replaced each pair of properties with one Item struct.
The problem I’m facing now is that I can’t find a way to have the same protection level I had before, with the 3 pairs of properties. I want everything outside MyClass to be able to get the properties inside the Item structs, but only MyClass and classes derived from it to be able to change the properties inside the Item structs.
How can I do such a thing? Is it even possible?
You can make your struct read-only to retain control over the values. This is a pattern used in parts of .NET:
Then you can create your properties the same way you did before, knowing that the values inside the struct will remain unchanged unless you go through the property setter.