Amber O
Amber O

Reputation: 67

Calling object of a method in another method

I am trying to use Instance Object below to call close() method. It gives an error: The name 'Instance' does not exist in the current context". Can anyone suggest what am I doing wrong.

public class Trial
{
     public static void Initialize()
    {
        IWebDriver Instance = null;
        Instance = new FirefoxDriver();
        Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
        Instance.Navigate().GoToUrl("www.google.com");
    }
     public static void Close()
     {
         Instance.Close();
     }


}

Upvotes: 0

Views: 1073

Answers (2)

JeffC
JeffC

Reputation: 25687

You should spend some time reading some articles about variable scope. Here's one such article but there are many, many more.

https://msdn.microsoft.com/en-us/library/ms973875.aspx

You originally declared Instance inside the Initialize() method. That means it can only be seen within the scope of that method. If you want to refer to it elsewhere, you have to declare it within the scope of where you want to have access to it. One way to do that in your code sample is to move the declaration of Instance into the Trial class. Once that is done, both the Initialize() and Close() methods are within it's (the class) scope so they both have access to the variable.

public class Trial
{
    static IWebDriver Instance = null;

    public static void Initialize()
    {
        Instance = new FirefoxDriver();
        Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
        Instance.Navigate().GoToUrl("www.google.com");
    }
    public static void Close()
    {
        Instance.Close();
    }
}

Upvotes: 3

John3136
John3136

Reputation: 29266

Instance is "local" to Initialize() and so can't be seen by Close() - you might want to look at making Instance a member of the Trial class so that all methods can see it.

Upvotes: 1

Related Questions