0

I have a class, which contains a simple data model class with properties. Only the outer class should be allowed to call the setters of the properties of the inner class. How can I achieve that?

public class Outer {
  public class Inner {
    public string Data { get; whatilookfor set; }
  }

  public Outer() {
    Inner test = new Inner() { Data = "Test" }; // This should work
  }
}

public class SomeOther {
  public SomeOther() {
    Inner otherTest = new Inner() { Data = "Other Test" }; // This should fail
  }
}
André Reichelt
  • 1,484
  • 18
  • 52
  • 3
    Hi there, I don't know if you came across with this [post](https://stackoverflow.com/questions/21439102/how-to-restrict-setting-a-property-of-innerclass-just-from-the-outer-class-in-c) take a look, it might help you. –  Jul 25 '19 at 07:06
  • @Bob Thank you. Looks like there is no easy way to do that. For my test project, I don't want to create such a spaghetti construction. But thank you anyways. – André Reichelt Jul 25 '19 at 07:13
  • Why don't you do `private class Inner` so that the Inner class can only be accessed from the Outer class? – ALFA Jul 25 '19 at 07:15
  • Not clear what is the relation between `SomeOther` and `Outer`. Here, `SomeOther` knows nothing about a `Inner` class. Should it be `SomeOther : Outer`? Or is `SomeOther` intended as another nested class of `Outer`? Here, it's not. – Jimi Jul 25 '19 at 07:20
  • My inner class is a data container. The outer class is a wrapper for that, which implements an enumerable of the data class. The idea is, that only the outer class should be able to modify the inner class, but the inner class must be serializable, because it is delivered over a web interface, – André Reichelt Jul 29 '19 at 06:42

0 Answers0