Roger
Roger

Reputation: 6527

declaring global variables from within a function?

Here's my code:

    private void connect()
    {
        try
        {
            textBox1.Text += "connecting... \r\n";
            button1.Enabled = false;

            DuplexChannelFactory<IfaceClient2Server> cf =
                    new DuplexChannelFactory<IfaceClient2Server>(
                        new CallbackImpl(),
                        new NetTcpBinding(),
                        new EndpointAddress("net.tcp://localhost:9080/service"));

            IfaceClient2Server srv = cf.CreateChannel();
            srv.StartConnection(name); /// need to make this one global!
            textBox1.Text += name + "connected!\r\n"; 
        }
        catch
        {
            button1.Enabled = true;
            textBox1.Text += "error connecting!\r\n";
        }
    }


    private void sendMsg()
    {
        srv.Message_Cleint2Server("Hello!");
        /// srv doesn't exist here.
    }

as you can see, the server object ( srv ) is being declared from with the connect() function, yet of course I need this object to be global, so that I would be able to access it from other functions, such as sendMsg as well.

What do you think might be the best way to do this?

Thanks!

Upvotes: 0

Views: 11867

Answers (4)

Richard Hooper
Richard Hooper

Reputation: 819

The best thing to do for this type of problem is to create a class that contains static members so you can set and get the values from it. This way you can access it from everywhere that the class can be see making it "global". Like this:

public class ApplicationController
{
    public static IfaceClient2Server Server { get; set; }
}

You may choose to implement custom get and sets to prevent issues or create the object as a part of the static constructor of the class.

Upvotes: 1

Joel Etherton
Joel Etherton

Reputation: 37533

My preference is to make a lazy-loaded property with a private setter. In this context, that would mean you would have to do the same thing with your cf object that creates the srv.

Upvotes: 1

Kendrick
Kendrick

Reputation: 3787

Declare it as a member variable (it doesn't need to be global...) Is there some issue you're trying to deal with that makes you not want to take that approach?

Upvotes: 1

Femaref
Femaref

Reputation: 61437

You need to make it an instance variable.

public class Foo
{
  private string instanceVariable;


  public void Set(string s)
  {
    instanceVariable = s;
  }
  public string Get()
  {
    return instanceVariable; //same value as "s" in "Set"
  }
}

Note: If exposing variables to the outside, use Properties.

Upvotes: 1

Related Questions