Plisken
Plisken

Reputation: 433

An object reference is required C# CS0120

This question has been asked to death but i cannot take from those answers what my problem is.

All i want to do is :

  1. Declare my global bool variable (used as a flag for later.)
  2. Run my method to do a check, in which it will change the global variable

Anybody able to explain why this isn't working? Thanks.

    class Program
    {
        public bool onVPN;

         static void Main(string[] args)
        {
            CheckVPN();
            CheckIfInternal();
            Console.WriteLine("Press enter to close...");
            Console.ReadLine();
        }
        public void CheckVPN()
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                //crude way to check if the VPN adapter is running
                if (adapter.Description == "VPN Adapter")
                {
                   onVPN = true;
                }

                else
                {
                    onVPN = false;
                }

            }
        }

Upvotes: 0

Views: 189

Answers (2)

styx
styx

Reputation: 1925

you have 2 options here

1.change CheckVPN() signature to static and the variable onVPN to static as well, you can find the reason why you have to add static here

2.create new class and put your code there as it is, and then on your main class you can do something like this

Class1 c = new Class1();
c.CheckVPN();

Upvotes: 0

madoxdev
madoxdev

Reputation: 3890

class Program
{
    public static bool onVPN;

     static void Main(string[] args)
    {
        CheckVPN();
        CheckIfInternal();
        Console.WriteLine("Press enter to close...");
        Console.ReadLine();
    }
    public static void CheckVPN()
    {
        NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface adapter in adapters)
        {
            //crude way to check if the VPN adapter is running
            if (adapter.Description == "VPN Adapter")
            {
               onVPN = true;
            }

            else
            {
                onVPN = false;
            }

        }
    }

Changes applied, are added static keyword to onVPN field, and to method CheckVPN.

More explanation can be found here: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0120

Upvotes: 2

Related Questions