Visakh V A
Visakh V A

Reputation: 320

Issue with Treeview item update when passing as a parameter

I have following test code, I am updating m_ClientTreeView by calling createTreeView(TreeView tree) method by passing it. But even treeview is a refrence type, the change is not reflecting back. I checked with ref and it is working properly.

 namespace TestRefType
 {
   public partial class Form1 : Form
   {
      public Form1()
      {
        InitializeComponent();
      }

      private void Form1_Load(object sender, EventArgs e)
      {
         ClientGUI objCGUI = new ClientGUI();
         createTreeView(objCGUI.m_ClientTreeView);
         //createTreeView(ref objCGUI.m_ClientTreeView);

         objCGUI.m_ClientTreeView.Dock = DockStyle.Fill;
      }

     private void createTreeView(TreeView tree)
     {
         tree = new TreeView();
         tree.Visible = false;
     }
}

  public struct ClientGUI
  {
     public System.Windows.Forms.TreeView m_ClientTreeView;
  }
}

What might be the reason?

Upvotes: 1

Views: 46

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

Although TreeView is a reference type but it doesn't mean you can change its reference when you pass it to a method.

When you pass a reference type to a method, you can change its members but you can not change reference of object. To change the reference of the object you need to use ref keyword in method signature and when passing the instance to the method.

Without using ref, when you pass objCGUI.m_ClientTreeView to createTreeView(TreeView tree) to method, in the method, tree is just a variable which points to a TreeView. You can access and change tree.SomeProperty, but if you say tree = new TreeView() then you just said the tree variable in your method scope point to a new TreeView. Outside of the method, objCGUI.m_ClientTreeView contains the value which it had before passing to the method.

Example

Here is a really simplified example about what you did:

TreeView t1 = null;
TreeView t2 = t1;
t2 = new TreeView();

What do you expect from t1 now?

Note 1: When using a reference type in a structure, you should be careful when using the structure. Although structures are value type but when copying, their reference types don't copy and keep the same references between different instance of that structure, for example if you add node to the TreeView of the copied structure, the node also will be added to the first instance of your structure.

Note 2: Here is a great article by Joseph Albahari about reference type and value type. It probably will solve most of your problems about the concept:

Upvotes: 2

Related Questions