20dka 20dka - 1 month ago 11
C# Question

How can I access an instance outside of the method it was created in?

I am working on a console app that transmits OutGauge data to an Arduino, but I'm stuck with the problem described below.

Here's the top of my code:

using System;
using InSimDotNet.Out;
using ArduinoDriver;
using ArduinoUploader.Hardware;
using ArduinoDriver.SerialProtocol;

class Program
{
static void Main()
{
var driver = new ArduinoDriver.ArduinoDriver(ArduinoModel.NanoR3, true);


I need to access
driver
(which I created in the
Main
method) in
outgauge_PacketReceived()
.
To be specific, I need to use its
Send()
method.

static void outgauge_PacketReceived(object sender, OutGaugeEventArgs e)
{
//I need driver.Send() here.
}

Answer

declare driver at the class level:

static ArduinoDriver _driver;

static void Main()
{
   _driver = new ArduinoDriver.ArduinoDriver(ArduinoModel.NanoR3, true);
   //...
}

You declare it as a class member, then still instantiate it in Main