R4D4
R4D4

Reputation: 1402

How can I organise these structures?

I have a number of different structs like below (obviously a little more involved and complicated), and am wanting to access private variables and methods from within methods within ABC while making those same variables and methods invisible from outside of the class MyMainClass; I know I could work around this with Reflection, but I'd rather not go down that route. I'm sure somebody here has had a similar problem - how did you get around it?

public class MyMainClass {

    public struct SStruct {
        private ulong myInternalVar;
        public ulong InternalVar{ get{ return myInternalVar; } }
    }

    public void ABC() {
        SStruct val1=new SStruct();
        val1.gElementID=101;
    }

}

Upvotes: 0

Views: 69

Answers (3)

dlev
dlev

Reputation: 48596

Since SStruct is declared nested within MyMainClass, the implication (at least whenever I see something like that) is that SStruct is intended to support MyMainClass, and not be used by outside classes. If that's the case, the easiest work-around to your problem is to declared the struct as private, and then make the private members public or internal. Now, other classes can't access the members (since they can't access the struct at all,) while MyMainClass can.

If you're actually using SStruct elsewhere, I would recommend declaring it outside of any other classes, so that it's clear it's meant to be used that way.

Finally, you should just avoid mutable value types in general. Create constructors that set the state you want, and then let the struct live out its life that way. If you need to "alter" it, then the methods that do so should return a newly created instance with the required state.

Upvotes: 3

InBetween
InBetween

Reputation: 32760

You can not achieve what you want if the nested types need to be public. The closest solution to what you are pretending is creating an internal setter, this way it would not be available outside the assembly. Anyhow, I am not sure what you are trying to achieve and why.

My advice, with the little information availabe, would be to consider implementing your structs as immutable types (mutable structs are evil) and then overload the constructor to set the internal state. This will not resolve the problem you are facing, it's just a piece of advice on your general design.

Upvotes: 0

Davita
Davita

Reputation: 9124

You could mark private fields as internal, so that fields won't be visible outside the assembly they reside.

Upvotes: 1

Related Questions