#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2013
    Posts
    9
    Rep Power
    0

    How to call an object from another method in C#


    Can anyone help a novice C# beginner? I'm attempting to call an object created in the same class
    but a different method. Both methods were called from another class. Below is simplied code.
    I've left out other code that the methods perform. An error indicates the "listener" object isn't
    recognized in the 2nd method. Thank you for any help your can offer.



    Code:
    // this 1st class calls methods of a 2nd class
        public class Lru_operation
        {
            // create an object of the 2nd class
            public Lru_Listen LruListen = new Lru_Listen();
        
            // this method calls two methods from other class 	
            public void LruOperation()
            { 	
                LruListen.ListenForAag();          // first method call
               
        	    LruListen.LruListenAccReq();       // second method call 
            }
        }
        
        // this is the 2nd class 
        public class Lru_Listen
        {
            // 1st method creates an object from a different class (HttpListener)
            public void ListenForAag()
            {
                HttpListener listener = new HttpListener();	
            }
        	
            // 2nd method calls 1st method's object to perform 
            // a method task from a different class
            public void LruListenAccReq()
            {
                HttpListenerContext context = listener.Getcontext();		
            }
        }
  2. #2
  3. Lord of the Dance
    Devshed Expert (3500 - 3999 posts)

    Join Date
    Oct 2003
    Posts
    3,614
    Rep Power
    1945
    You will have to define the variables outside the functions. Take a look at Declaring Member Variables

IMN logo majestic logo threadwatch logo seochat tools logo