-1

I have the nub of the code like this:

public class OuterClass
{
    public static InnerClass GetInnerClass()
    {
        return new InnerClass() { MyProperty = 1 };
    }

    public class InnerClass
    {
        public int MyProperty { get; set; }
    }
}

what is the solution to property named MyProperty just be settable from the InnerClass and the OuterClass, and out of these scopes, MyProperty just be readonly

Amir Sherafatian
  • 2,083
  • 2
  • 20
  • 32
  • 1
    Do you *have* to be able to set it after construction at all? Can you not just make it a constructor parameter and have a read-only property? – Jon Skeet Jan 29 '14 at 18:12
  • 1
    You can approach this with `internal`, with the classes in a separate assembly. But you really shouldn't' be wanting to. – H H Jan 29 '14 at 18:16
  • 1
    I'm curious as to a real-world non-contrived example for the need for this. It certainly seems like a convenient feature to have, but I suspect that the relationship between `OuterClass` and `InnerClass` may be calling for a different structure than what's being attempted here. – David Jan 29 '14 at 18:41
  • @JonSkeet: i can not make it a constructor parameter – Amir Sherafatian Jan 29 '14 at 19:07
  • @Henk Holterman: i can not set it as `internal` – Amir Sherafatian Jan 29 '14 at 19:08

2 Answers2

3

There is no protection level for that. internal is the tightest you can use, which is limited to files in the same assembly. If you cannot make it a constructor parameter as has been proposed, you could use an interface:

public class OuterClass
{
    public static InnerClass GetInnerClass()
    {
        return new InnerClassImpl() { MyProperty = 1 };
    }

    public interface InnerClass
    {
        int MyProperty { get; }
    }
    private class InnerClassImpl : InnerClass
    {
        public int MyProperty { get; set; }
    }
}
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98
  • `InnerClassImpl` should not implement `MyProperty` from interface as only getter ? – Amir Sherafatian Jan 29 '14 at 18:41
  • 1
    @am1r_5h: It implements a getter, so that satisfies the interface. The setter is implementation-specific and is only seen by `OuterClass` in this case. (Which is necessary to set the value in the object initializer.) – David Jan 29 '14 at 18:42
2

I'm afraid there is no access modifier which allows that. You can create IInnerClass interface and make the property readonly within interface declaration:

public class OuterClass
{
    public static IInnerClass GetInnerClass()
    {
        return new InnerClass() { MyProperty = 1 };
    }

    public interface IInnerClass
    {
        int MyProperty { get; }
    }

    private class InnerClass : IInnerClass
    {
        public int MyProperty { get; set; }
    }
}
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263