I'm a beginner in c# and trying to do multithreading.
I got 2 error that M and N need to be reference to be used in methods below.
I thought if I define it as public int M,N;, they should be able to use in any methods in the class.
Can somebody help me, please?

Error 1 An object reference is required for the non-static field, method, or property (for both M and N.)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestMultithread2
{
    public class Program
    {
        public int M, N;

        static void Main(string[] args)
        {
            Console.WriteLine("input numbers of steps");
            int N = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("input numbers of trials");
            int M = Convert.ToInt32(Console.ReadLine());

            Thread U_1Thread = new Thread(new ThreadStart(GetU_1));
            Thread U_2Thread = new Thread(new ThreadStart(GetU_2));

            U_1Thread.Start();
            U_2Thread.Start();

            U_1Thread.Join();
            U_2Thread.Join();

            Console.WriteLine("Finish");
            Console.ReadLine();
        }





        static void GetU_1()
        {
            int newM = M; //this is where I got the error.
            int newN = N;

            Random rnd = new Random();
            int row, col;
            double[,] U_1 = new double[newM / 2, newN];
            for (row = 0; row < newM / 2; row++)
            {
                for (col = 0; col < newN ; col++)
                {
                    U_1[row, col] = Math.Sqrt(-2 * Math.Log(rnd.NextDouble())) * Math.Sin(2 * Math.PI * rnd.NextDouble());//Using Box Muller Random Method. 
                }
            }
            

        }

        static void GetU_2()
        {
            Random rnd = new Random();
            int row, col;
            double[,] U_2 = new double[10 / 2, 10];
            for (row = 0; row < 10 / 2; row++)
            {
                for (col = 0; col < 10; col++)
                {
                    U_2[row, col] = Math.Sqrt(-2 * Math.Log(rnd.NextDouble())) * Math.Sin(2 * Math.PI * rnd.NextDouble());//Using Box Muller Random Method. 
                }
            }
            
            
        }



    }
}

because M and N aren't declared static, they are instance variables. This means you need to create an instance of the class to use them. That is the error you are getting. If you don't want to create an instance, then you need to declare them as static static int M, N; .

But if you continue along this line in your future code, you are losing the benifits of Object Orientation. I'd suggest you study up on static, instance and method variables and scope.

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.