user1108948
user1108948

Reputation:

Make dynamic object global

My original code:

public partial class LineInstance
{
   EventWaitHandle _stopHandle;
   Private int _linenumber;
   // many variable;
   public LineInstance(int linenumber, EventWaitHandle stopper)
   {
      _stopHandle = stopper;
  _linenumber = linenumber;
      // blah
   }    

   private string Menu()
   {
      dynamic api = new Http("http://80.56.16.214/MyServices/MyData.svc");
  var reply = api.GetId(Id: "888");
  var response1 = reply.Response;
  // blah blah
}
 }

Now I want to make these

dynamic api = new Http("http://80.56.16.214/MyServices/MyData.svc");
var reply = api.GetId(Id: "888");
var response1 = reply.Response;

to be global because I want to use in other methods in this class. I tried move them to the area before class constructor

updated:

public partial class LineInstance
{
EventWaitHandle _stopHandle;
private int _linenumber;
dynamic api = new Http("http://80.56.16.214/MyServices/MyData.svc");
var reply = api.GetId(Id: "888");
var response1 = reply.Response;
          // blah blah

but I got an error:

Error: “an object reference is required for the non-static field, method or property

How do I modify my code to make them be global?

Upvotes: 0

Views: 2740

Answers (2)

Max Yankov
Max Yankov

Reputation: 13297

To adress these properties from other methods of the class, you don't have to make them static. Your updated code is almost right. Here's what you need to do:

public partial class LineInstance
{
   EventWaitHandle _stopHandle;
   Private int _linenumber;
   dynamic api;
   dynamic reply;
   dynamic response1;

   // many variable;
   public LineInstance(int linenumber, EventWaitHandle stopper)
   {
      _stopHandle = stopper;
  _linenumber = linenumber;
      // blah
   }    

   private string Menu()
   {
  api = new Http("http://80.56.16.214/MyServices/MyData.svc");
  reply = api.GetId(Id: "888");
  response1 = reply.Response;
  // blah blah
  }
 }

As you see, the only thing I've changed is I initialize the fields in the constructor, not the class body — that way there's no error.

Upvotes: 0

bash.d
bash.d

Reputation: 13207

Define your object as static if you want to be able to use it without any specific instance of your class

public partial class LineInstance
{
private static dynamic api;
EventWaitHandle _stopHandle;
private int _linenumber;
    // many variable;
public LineInstance(int linenumber, EventWaitHandle stopper)
{
_stopHandle = stopper;
_linenumber = linenumber;
    // blah
 }  

You should provide a public property to access the object

public static dynamic Api{
 get{ return api; }

}

Apart from that, there are no global variables in C# and you should avoid them by any means!

Upvotes: 1

Related Questions