0

I am new to C# and working with methods. My attempt was to create a seperate method for logging the user in. The Code looks something like

public IWebDriver bot;


void DataGrabber(object sender, RoutedEventArgs e)
{
    string user = "...";
    string pass = "...";

    UserLogin(user, pass);

    bot.Navigate().GoToUrl("https://example.com/data"); //NullReferenceException gets raised here
}

static IWebDriver UserLogin(string user, string pass)
{
    IWebDriver bot = new ChromeDriver();
    
    bot.Navigate().GoToUrl("https://example.com/loginform");
    // Login Stuff....
    return bot;

}

how do I properly define bot, so that the DataGrabber() method knows what it is?

I removed the public IWebDriver bot; definition in the beginning but that just results in the bot not being recognized as a variable at all ("The name "bot" is not available in the current context").

I also attempted to move the UserLogin() method before the DataGrabber() method, but this did not help (bot still not recognized within DataGrabber() function).

I am certain that this is an easy thing to answer, however searching online did not return anything useful

  • You never assign anything to the field `bot`. `async void` is a bug too, as such methods can't be awaited. There's nothing asynchronous in that method either. The `async void` signature is *only* meant for asynchronous event handlers. `async` doesn't make a method asynchronous, it tells the compiler to generate the code needed to use `await` to await asynchronous calls – Panagiotis Kanavos Aug 10 '23 at 08:50
  • Selenium doesn't have asynchronous methods so the only way to avoid blocking when making Selenium calls is to use `Task.Run`. If you really want asynchronous calls, check Playwright – Panagiotis Kanavos Aug 10 '23 at 08:51

1 Answers1

1

You return (the local variable) bot from UserLogin, but you never assign it to the class-level field. In other words: the bot in UserLogin is different from the bot in DataGrabber.

One solution:

in DataGrabber, change

UserLogin(user, pass);

to

bot = UserLogin(user, pass);

to set the class-level field.

For further details about that exception, see What is a NullReferenceException, and how do I fix it?

Hans Kesting
  • 38,117
  • 9
  • 79
  • 111