Reputation: 1717
I'm starting with C# and I got a problem.
I created a "Windows Form Application" project.
I have a form class named form1 and I added a UserControl class named usercontrol1. In usercontrol1, I have a public function named test which returns 123.
For some reason I can't do this:
private void Form1_Load(object sender, EventArgs e)
{
UserControl usercontroltest = new usercontrol1();
usercontroltest.test();
}
The error I get is "user control does not contain a definition for"
Upvotes: 1
Views: 2171
Reputation: 1503944
This is because you've declared your variable to be of type UserControl
. That means the compiler will only let you use members declared in UserControl
and the classes it inherits from. The actual object is still of type usercontrol1
at execution time, but the compiler only cares about the compile-time type of the variable you're trying to use to call the method.
You need to change the declaration to use your specific class:
usercontrol1 usercontroltest = new usercontrol1();
Or you could use an implicitly typed local variable, which would have exactly the same effect:
var usercontroltest = new usercontrol1();
That will fix the immediate problem, but:
Upvotes: 6
Reputation:
UserControl usercontroltest = new usercontrol1();
While this allocates a new usercontrol1
, it assigns it to its base class, UserControl
. UserControl
has no test()
method.
You probably want:
usercontrol1 usercontroltest = new usercontrol1();
instead.
Upvotes: 2