C# Function question

S

Scott Schaffer

Hello,
This should be a simple problem to solve, but I'm fairly new to C# and
have been wracking my brains to no avail. I created a new Console
Application in C# beta 2, and entered the following:

using System;
using System.Collections.Generic;
using System.Text;

namespace Test2
{
class Program
{
static void main (string[] args)
{
string a = "qwert";
string b = GetStuff( );
string c = a + b;
Console.WriteLine(c);
}

public string GetStuff( )
{
string c = "poiuy";
return c;
}
}
}

When I compile this, I get the error: "An object reference is required
for the nonstatic field, method, or property 'Test2.Program.GetStuff( )' for
the line: string b = GetStuff( );

I'm not entirely sure what the problem could be, and would appreciate it
if someone help. Thanks.

Scott
 
O

Ollie Riches

you require the following:

class Program
{
static void main (string[] args)
{
Program p = new Program();
string a = "qwert";
string b = p.GetStuff( );
string c = a + b;
Console.WriteLine(c);
}

...
...


HTH

Ollie Riches
 
P

Paul E Collins

Scott Schaffer said:
When I compile this, I get the error: "An object reference
is required for the nonstatic field, method, or property
'Test2.Program.GetStuff( )' for the line: string b = GetStuff( );

If you change GetStuff to be a "static" method, like Main, it will
compile.

Alternatively, you can put your code in one or more separate classes
(a better idea for large projects) and then Main could create an
instance (Thing t = new Thing();) and call non-static methods on the
instance of the class. Look up "static" in the help to learn more
about static vs. class methods.

P.
 
?

=?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?=

Scott said:
Hello,
This should be a simple problem to solve, but I'm fairly new to C# and
have been wracking my brains to no avail. I created a new Console
Application in C# beta 2, and entered the following:

To call non-static methods you need an object instance.

This means that since main is a static method, it cannot call other
non-static methods of the same class, unless you first construct an
object (Program object) and call the method through that.

The solution is either:

1. Construct an instance of Program and call GetStuff through that:

Program p = new Program();
string b = p.GetStuff();

or:
2. Make GetStuff a static method as well
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top