Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I have seen a code as shown below
C#
Class Sample
      {
           AddSubPage("Title",new ServerControl());
           private void AddSubPage(string title, Control subPage)
           {
          
           }
      };
      Class ServerControl
      {
         public ServerControl()
         {
             InitializeComponent();
         }
      };

My doubt is regarding the second parameter.What is actually passing in the

second parameter.I know 'Control' is the base class of all controls in form.So how

to assign new ServerControl() to Control object.

'new ServerControl()' means just calling a constructor.(See the code).Then what is

actually passing here.

Note:Class ServerControl is inherits a class called DBMigrationSubPageBase which

inherits a class 'UserControl'

Thanks in advance
Posted
Updated 27-Nov-11 19:11pm
v2
Comments
Manoj K Bhoir 28-Nov-11 1:12am    
Edited to add <pre> tag.

1 solution

What gets passed to AddSubPage is an instance of whatever type you call the method with, as long as it derives from Control. If not, the compiler will throw an error. Once it has been passed, you will have to explicitly convert to the type of control actually passed.

If you do a quick test, something like this:-
C#
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            AddServerControl("New Server Control", new ServerControl());
        }

        void AddServerControl(string title, Control subpage)
        {
            //Should do checking here to ensure it is Server control.
            ServerControl ctrl = subpage as ServerControl;
            ctrl.Talk("I am a Server control!");
        }
    }

    class ServerControl:Control
    {
        public ServerControl()
        {

        }

        public void Talk(string message)
        {
            MessageBox.Show(message);
        }
    }



you will see that the messagebox is displayed, which means that the object passed IS actually an instance of ServerControl.

Hope this helps
 
Share this answer
 
Comments
kutz 2 28-Nov-11 2:11am    
But it is not getting any compilation error.

class ServerControl:DBMigrationSubPageBase
{

}

class DBMigrationSubPageBase : UserControl
{
}
Wayne Gaylard 28-Nov-11 2:15am    
You won't get a compiler error because UserControl is derived from control, and so it is correct to pass an instance of ServerControl. What exactly were you expecting ?
kutz 2 28-Nov-11 2:21am    
Ok thank you.Now I it is cleared.
Wayne Gaylard 28-Nov-11 2:24am    
Glad to help.

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