• Register
Welcome to Kodlogs, programming questions and answer website.
0 votes
26 views

Problem:

I am getting following error message:

'an object reference is required for the nonstatic field method or property' What might be the cause for this error?

by (330 points)  

1 Answer

0 votes

Solution:

This error happens when you try to call a non static property from static method.

You  need to create an object reference for the nonstatic field, method, or property 'member'.

      First of all object instance need to be created  to use a non-static field, method, or property.

    

     The Error Code

     using System;

     using System.Collections.Generic;

    using System.Linq;

    using System.Text;

namespace text1

{

    class nonStaticEx

    {

        public int setValues(int no1, int no2)

        {

            return no1 + no2;

        }

        static void Main(string[] args)

        {

            float i;

            var count = 10;

            Console.WriteLine("Hello World");

            Console.ReadLine();

            for (i = 1; i <= 10; i++)

                {   Console.WriteLine("This is non static test");

                    Console.WriteLine(count);

                };

            string x, y;

            x = "vu anh";

            y = "dep trai";

            Console.WriteLine(x + " " + y);

            int val;

            val = setValues(3, 4);

            Console.WriteLine(i);

            Console.ReadLine();

        }

    }

}

The right code

using System;

     using System.Collections.Generic;

    using System.Linq;

    using System.Text;

namespace text1

{

    class nonStaticEx

    {

        public int setValues(int no1, int no2)

        {

            return no1 + no2;

        }

        static void Main(string[] args)

        {

            float i;

            var count = 10;

            Console.WriteLine("Hello World");

            Console.ReadLine();

            for (i = 1; i <= 10; i++)

                {   Console.WriteLine("This is non static test");

                    Console.WriteLine(count);

                };

            string x, y;

            x = "vu anh";

            y = "dep trai";

            Console.WriteLine(x + " " + y);

            int val;

            val = setValues(3, 4);

int val;

nonStaticEx nSE = new nonStaticEx();

val= nSE.pt(3, 4);

            Console.WriteLine(i);

            Console.ReadLine();

        }

    }

}

Conclusion:

So here we have used instance of class nonStaticEx inside static method.

by (3.3k points)  
...