Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Static field error 1

Status
Not open for further replies.

tshad

Programmer
Jul 15, 2004
386
US
I am trying to pass back an instance of an object from a method but I get the error:

From a console program:
Code:
 class Program 
   {
      static void Main(string[] args)
      {
         DataSet temp = GetDataSet();

         DataSet temp2 = new DataSet();

         Console.ReadLine();
      }


      public DataSet GetDataSet()
      {
          return new DataSet();
      }
   }

The object temp2 gets created fine.

But I get a compiler error on the GetDataSet() method:

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

I do this all the time in my normal aspx pages, why doesn't it work here?

Thanks,

Tom
 
Your method isn't static, while you're trying to call it from a static method. Normally when calling a method like that it would implicitly be a this.GetDataSet(); call, but there is NOT 'this' when in a static method.

Either do your call outside of a static method, and inside an instance of Program, or change GetDataSet to be static.

Code:
[COLOR=#0000FF]class[/color] [COLOR=#2B91AF]Program[/color]
{
    [COLOR=#0000FF]static[/color] [COLOR=#0000FF]void[/color] Main([COLOR=#0000FF]string[/color][] args)
    {
        [COLOR=#2B91AF]DataSet[/color] temp = GetDataSet();
 
        [COLOR=#2B91AF]DataSet[/color] temp2 = [COLOR=#0000FF]new[/color] [COLOR=#2B91AF]DataSet[/color]();
 
        [COLOR=#2B91AF]Console[/color].ReadLine();
    }
 
 
    [COLOR=#0000FF]public[/color] [COLOR=#0000FF][b]static[/b][/color] [COLOR=#2B91AF]DataSet[/color] GetDataSet()
    {
        [COLOR=#0000FF]return[/color] [COLOR=#0000FF]new[/color] [COLOR=#2B91AF]DataSet[/color]();
    }
}
 
That makes sense.

Thanks,

Tom
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top