0

I'm working on a windows forms application in c# and I can't figure out why I can't instantiate a class object from my form code. I have several classes, and from within all of those I can instantiate instances of the other classes publicly or just within methods with no problem. However, when I try to instantiate one of those classes from my main form, it doesn't work.

enter image description here

It doesn't even recognize that I've just created an instance of the class. The real kicker is that I can successfully instantiate a class from inside a method in my frmMain class:

 private void Form_Load()
    {
    long deltaTime; int i; int page;

      if (releaseMode)
      {
          modCanCable can = new modCanCable();
          can.WaitWhileBusy();
      }

All of the classes and form classes are under the same namespace too. Please let me know if you need to me to include any more information to help me find an answer!

5
  • 3
    To call a method of a class or access member/property you should do it in a method or a getter setter of a property. You can not just do it in class scope. Feb 19, 2015 at 15:10
  • You can only declare the global variable at the class level. Making use of that global variable must be done inside a property, method, or function. Feb 19, 2015 at 15:12
  • @user3021830 But I need to declare a public variable that is of a type of an enumerator from another class in this frmMain class. How would I do this then? Feb 19, 2015 at 15:14
  • @MikkelBang, like you would any other variable private EnumeratorClass VariableName; See my answer below. Feb 19, 2015 at 15:16
  • public EMyEnum PublicProperty { get { otherclass cls = new otherclass(); return cls.ClassEnum; } } Feb 19, 2015 at 15:17

3 Answers 3

1

You can only declare the global variable at the class level. Making use of that global variable must be done inside a property, method, or function.

For a global enumerator, declare it like you would any other variable

private EnumeratorClass VariableName;

Example (following naming conventions)

private MyEnum _myVariableName;
1

In C# all code has to be inside of a method. The line modCanCable can = new modCanCable(); declares a private field and uses a field initializer to initialize it to a new modCanCable instance. Any other refrence to the can field must be inside of a method body.

0

It must be done within a method or constructor. You cannot put it just in the class.

public partial class frmMain : Form
{
    modCanCable cab = new modCanCable();
    public frmMain()
    { 
         cab.property = "asd";   
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.