Calling Objects from other Classes

Let me see if i can explain this right....

I've got a class FSaver.cs. In this class, i create a new instance of another class called Rest.cs

Rest Book = new Rest();

In FSaver, i can call objects such as Book.hello(); That works fine.

But inside Book, I cant call anything from FSaver. Does this make sense Is there a way to make classes equal, and not parent/child oriented

Thanks!
Jonathan




Answer this question

Calling Objects from other Classes

  • SuperJeffe

    You'd have to pass the instance of FSaver to the Rest instance.  I'd suggest you make a constructor that takes one:



    public class Rest
    {

      private FSaver _saver;

      public Rest(FSaver saver)
      {
        _saver = saver;
      }

      public void hello()
      {
        _saver.save();
      }
    }
    public class FSaver
    {
       public void DoSomething()
       {
          Rest Book = new Rest( this);
          Book.hello();

          //And so on
        }
    }

     

    Remember, you're not calling a classes method, you're calling methods on an instance of that class - so For your Book instance to call into FSaver, it needs an instance to call it on.    (The other possibility is to call into static methods, but that didn't seem what you wanted)

     


  • Calling Objects from other Classes