Monday, August 31, 2009

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

  • When you are creating a Console application you might come across this error message.
  • And most of the time,if you are not instantiating the object of the class and calling the function you might get this error.
In console application, The initial method called by CLR is static void Main()
Since the method is static, you dont need to create object to instantiate the class....when you are trying to access a method from static class (here class name is Program ) you will get an error Error 1 An object reference is required for the non-static field, method, or property

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

namespace ConsoleApplication1
{
class Program
{
private void func(string someName)
{

try
{
for (int i = 1; i <= tot; i++)
{
......
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static void Main(string[] args)
{
string someName;
try
{
func(someName);//It will throw error here
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("The End");
}
}
}
}


So use like this

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

namespace ConsoleApplication1
{
class Program
{
private void func(string someName)
{
try
{
for (int i = 1; i <= tot; i++)
{
......
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static void Main(string[] args)
{
string someName;
Program classObj=new Program(); //Instantiate
try
{
classObj.func(someName); //If you dont want create an object for your class you can use func(someName) and change the function definition to private static void func(string someName)
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("The End");
}
}
}
}

If you dont want create an object for your class you can use func(someName) and change the function definition to private static void func(string someName)

No comments:

Post a Comment