-1

So I am pretty new at C# and most of my programming experience has actually come from years of PHP work. As far i can tell I've declared my variables correctly inside of my class. Yet, inside of my Main method I am getting compiler error CS0120 that the 'isnegative' variable does not exist in the current context.

Are variables not class wide?

namespace ConsoleApplication1
{
class Program
{
    public int isnegative;
    static void Main()
    {
        isnegative = 0;
        for (int i; i = 0; i < 10; i++;)
        {
            if (isnegative == 0)
            {
                i = i;
                isnegative = 0;
            }
            else
            {
                i = i * (-1);
                isnegative = 1;
            }
            Console.WriteLine(i);
        }
    }
}
  • 1
    Only ***static*** varibles and members are visible to other ***static*** members. Here ***Main*** is static but ***isNegative*** is an *instance* member rather than a *static* one.. – Pieter Geerkens May 27 '16 at 23:02

2 Answers2

1

You should be able to correct the problem by making your variable declaration static (the same as your Main method).

public static int isnegative;

But there are also some problems with the way you have written your for statement. The following changes will allow your program to function correctly:

namespace ConsoleApplication1
{
    class Program
    {
        public static int isnegative;

        static void Main()
        {
            isnegative = 0;
            for (int i = 0; i < 10; i++)
            {
                if (isnegative == 0)
                {
                    i = i;
                    isnegative = 0;
                }
                else
                {
                    i = i*(-1);
                    isnegative = 1;
                }
                Console.WriteLine(i);
            }

            Console.ReadLine();
        }
    }
}
David Tansey
  • 5,813
  • 4
  • 35
  • 51
0

Are variables not class wide?

Yes, they are.

If you look at your main declaration:

static void Main()

You are working in a static method. Static methods can only work with static class variables. Because they can be called without any instance, instead of non-static variables which require an instance to exist.

So, to correct your issue, declare your isnegative variable as static or declare it in your main. And you should be fine ;)

romain-aga
  • 1,441
  • 9
  • 14