Click here to Skip to main content
14,699,613 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
How can i acess a variable inside a class,and this class is inside an another class?
Thanks for the atention.
Posted

1 solution

Unlike Java, in C# there is no implicit reference to an instance of the enclosing class.

You need to pass such a reference to the nested class. A typical way to do this is through the nested class's constructor.

Here an example of how to access field in the enclosing class from the nested class. Take a look at this article as well please: A Tutorial on Nested Classes in C#[^]

public partial class Form1 : Form
{
    private Nested m_Nested;

    public Form1()
    {
    	InitializeComponent();

    	m_Nested = new Nested(this);
    	m_Nested.Test();
    }

    private class Nested
    {
    	private Form1 m_Parent;

    	protected Form1 Parent
    	{
    		get
    		{
    			return m_Parent;
    		}
    	}

    	public Nested(Form1 parent)
    	{
    		m_Parent = parent;
    	}

    	public void Test()
    	{
    		this.Parent.textBox1.Text = "Testing access to parent Form's control";
    	}
    }
}
   
v2
Comments
   
A good one.
A couple on notes: 1) accessible members of the nested class need to be public only to be accessed from outside assembly, but in most cases, they are used only by the outer class (not always); so members are either private or internal, more typically; 2) The names like m_Parent violate really good Microsoft naming conventions; I would advise to avoid it.
(I voted 4 this time.)
—SA
Leo Chapiro 19-Jun-13 9:07am
   
Thank you, Sergey, I see :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900