-4
namespace ConsoleApplication
{

    class Program
    {
        static void Main()
        {
            int val = 10;
            fnctest(val);
            Console.WriteLine(val);
        }
        void fnctest(int val)
        {
            val = 200;
        }
    }
}

I am getting an Error:

An object reference is required for the non-static field, method,
or property 'ConsoleApplication'

What can I do to resolve this error?

dcaswell
  • 3,137
  • 2
  • 26
  • 25
vani
  • 41
  • 1
  • 3
  • read an understand this and linked articles http://msdn.microsoft.com/en-us/library/aa645766(v=vs.71).aspx – dkackman Oct 20 '13 at 13:08

3 Answers3

4

Make your fnctest method static or instantiate your class and call your method.

static void Main()
{
   int val = 10;
   fnctest(val);
   Console.WriteLine(val);

}
static void fnctest(int val)
{
   val = 200;
} 

Or

static void Main()
{
   int val = 10;
   Program p = new Program();
   p.fnctest(val);
   Console.WriteLine(val);

}
void fnctest(int val)
{
   val = 200;
}

Plesae read Static Classes and Static Class Members (C# Programming Guide)

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
0

Declare fnctest as static

Like this

public static void fnctest(int val)
{
    val = 200;
}

BTW (Not related to question):

I think you trying to find difference between value type and reference type. val value is changed in method and then printed to see if there is any change in its value. In that case you should also learn about out parameter.

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
0

main method is static and hence you can only call static methods from main..

Also you should pass the parameter by reference incase you want to change the original value passed to the method

So,your method should be

static void fnctest(ref int val)
{
    val = 200;
}

Your method call should be

fnctest(ref val);
Anirudha
  • 32,393
  • 7
  • 68
  • 89