0

I got a struct S as nested declaration in a class C, where I'd like to refere to members of C in the constructor of S:

public class C {
    private int class_state = 0;
    
    private struct S {
        public int struct_state;
        
        public S () {
            struct_state = class_state;
        }
    }

    public void foo (int state) {
        class_state = state;
    }
    
    public void bar () {
        S s = new S();
    }
}

Yielding an error, that class_state is non-static and therefore needs an reference to an instance of C.

Is there an implicit way to tell struct S to reference the instance it is instanciated in?

2
  • No, The struct has no idea which instace of the enclosing class is constructing it. Commented Jul 31, 2021 at 13:35
  • What is the problem with just passing in this to the constructor of S? Commented Jul 31, 2021 at 13:41

1 Answer 1

1

No. Unlike in Java, C# Nested Types don't have an "imilicit" or "automatic" reference to the instance of the enclosing type.

"A nested type has access to all of the members that are accessible to its containing type. It can access private and protected members of the containing type, including any inherited protected members."

but:

"To access the containing type, pass it as an argument to the constructor of the nested type. "

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.