开发者

Problem with assigning variable C#

开发者 https://www.devze.com 2023-03-30 18:27 出处:网络
When I return the string timeTaken, it is null, and it says this on the IDE to, although it has been defined in the main method (TimeSpan timeTaken = timer.Elapsed;)

When I return the string timeTaken, it is null, and it says this on the IDE to, although it has been defined in the main method (TimeSpan timeTaken = timer.Elapsed;)

class Program
{    
    public static string timeTaken;    

    static void Main(string[] args)
    {                
        HttpWebRequest request = (Htt开发者_如何学PythonpWebRequest)WebRequest.Create(firstline);    
        Stopwatch timer = new Stopwatch();
        timer.Start();               
        using (var response = request.GetResponse());
        timer.Stop();    
        TimeSpan timeTaken = timer.Elapsed;
        ...
    }
}            

How can I output timeTaken?


You define a local variable with the same name

TimeSpan timeTaken

which hides your static class field.

To output the value of timer.Elapsed you could write something like this:

Console.WriteLine("{0}", timer.Elapsed);


There is two timeTaken variable, one local to rthe Main function, the other one is a static member of the class. To explicitly refer to the string one use Program.timeTaken. Anyway is better if you refactor the code to have different names.


You probably want something more like this:-

class Program
{
  public static string timeTaken;
  static void Main(string[] args)
  {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(firstline);
    System.Diagnostics.Stopwatch timer = new Stopwatch();
    timer.Start();
    using (var response = request.GetResponse())
    timer.Stop();
    timeTaken = timer.Elapsed.ToString();
  }
}


You made a simple mistake: you define the variable "timeTaken" once again inside static void Main(...) on the line

TimeSpan timeTaken = timer.Elapsed;

This will shadow the static definition. To get back to the static class field use

Program.timeTaken = ...

think about naming (for example name your static field _timeTaken or just use

timeTaken = timer.Elapsed;

instead of

TimeSpan timeTaken = timer.Elapsed;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号