Search code examples
c#.netstopwatch

Problem with assigning variable C#


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 = (HttpWebRequest)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?


Solution

  • 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);