I am trying to teach myself C#. I was working on an example when I came across something of interest (to me anyway), and none of my resource material explains why this happens. Can some one explain why this happens.

The code below works as it should

//calc test
//3/16/2010

public class calctest
{

static void Main()

{
   double height = 5.5;
    double width = 5.5;
    double area;

area = height * width;
System.Console.WriteLine("area = {0}", area);

}
}

The code below however causes the following errors

Error 1 An object reference is required for the non-static field, method, or property 'calctest.area'

Error 2 An object reference is required for the non-static field, method, or property 'calctest.height'

Error 3 An object reference is required for the non-static field, method, or property 'calctest.width'

Can any one explain why?

//calc test
//3/16/2010

public class calctest
{

double height = 5.5;
double width = 5.5;
 double area;

static void Main()

{
   

area = height * width;
System.Console.WriteLine("area = {0}", area);

}
}

In your first listing, the variables you defined are local to the Main method and work as they should, as you have seen. In the second example, the variables are instance members of the class. Main, however, is a static method, which means it simply applies to calctest, not individual instances of calctest objects.

In order to use instance members of a class, you must instantiate the class. Otherwise, to access them without an instance, the members must be static.

public class calctest
{
    double height = 5.5;
    double width = 5.5;
    double area;

    static void Main()
    {
        calctest test = new calctest();
        test.area = test.height * test.width;

        System.Console.WriteLine("area = {0}", test.area);
        System.Console.Read();
    }
}

Or

public class calctest
{
    static double height = 5.5;
    static double width = 5.5;
    static double area;

    static void Main()
    {

        area = height * width;

        System.Console.WriteLine("area = {0}", area);
        System.Console.Read();
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.