-
December 17th, 2013, 05:03 PM
#1
How to call an object and method 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();
}
}
-
December 20th, 2013, 04:34 PM
#2
Re: How to call an object and method from another method in C#
You've defined HttpListener listener inside the ListenForArg method, so the listener.Getcontext() call made from LruListenAccReq() fails.
The solution is to move the declaration of listener into the class level.
Code:
// this is the 2nd class
public class Lru_Listen
{
HttpListener _listener;
// 1st method creates an object from a different class (HttpListener)
public void ListenForAag()
{
_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();
}
}
Btw, this is the quick and dirty way to change scope. It isn't the real world way because you have a dependency of the ListenForAag method within the LruListenAccReq method. This forces callers of your class to call the methods in a certain order. In general you want to avoid doing this sort of thing (because callers will not always understand such dependencies).
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|