Tech Off Thread

7 posts

Forum Read Only

This forum has been made read only by the site admins. No new threads or comments can be added.

Problem with static functions

Back to Forum: Tech Off
  • User profile image
    manuelhjoao

    Hey folks! Here’s my dilemma, I’m working with a few static functions. I need to populate a TreeNodes Collection. My question is how can I access a non static member from a static function?

  • User profile image
    amotif

    You'll need an instance of the class to call a non-static method on that instance. You'll have to find some way of getting a reference to that instance to your static method.

    (I suspect that because your static method is a callback this won't please you much...)

  • User profile image
    manuelhjoao

    Yeah its driving me crazy

  • User profile image
    JohnAskew

    You are calling static methods from an object in a library?

  • User profile image
    amotif

    Maybe you could fill in a few details for us--is this callback being called (back) from some particular API that you're calling?

  • User profile image
    Jorgie

    That should not be a problem as long as you pass in the object.

    Assuming class ClassX has a static method ClassX.SM(ClassX i), and a non-static method ClassX.NSM this should work:

    ClassX myX = new ClassX();

    ClassX.SM(myX);

    Now SM can call i.NSM().

    You have to pass the instance of the object in to give the static method something to work with since inside a static method you cant use 'this' to refer to the current instance since there isnt one.

    At least that works in my head, trying it now.

    Jorgie

     

  • User profile image
    Jorgie

    Ok, I was right, it works.... Not sure how useful it is, but it works...

    class ClassX
    {
      private string name;
      public string Name { get { return name; } }
      public ClassX(string MyName) { name = MyName; }
      public static void ShowName(ClassX x)
      {
        MessageBox.Show(x.name);
      }
    }

    So now I can create an instance of my class:

      ClassX bob = new ClassX("Robert");

    And use the static method ShowName to show its name:

      ClassX.ShowName(bob);

    This is the only way I can think for it to work as you must provide a way for the static method to get a hold of an instance of the class in order to access a non-static method or in this case property (which uses the non static method GET method for 'Name').

    Hope that helps!

    Jorgie

Conversation locked

This conversation has been locked by the site admins. No new comments can be made.