C# Can't access public function from different class

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"

Jon Skeet
people
quotationmark

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:

  • Are you sure you really want to create a new instance here, rather than using one which is already on your form?
  • You should get into the habit of following .NET naming conventions as soon as possible

people

See more on this question at Stackoverflow