Reputation: 19
I'm new in C#, could you please tell me that what's my problem here. I know it's very simple for you but it's not for me :(
My short code :
class A
{
private int B;
public void b(){ }
public void c(){ B = b( );}
static void Main ( string [ ] args )
{
c();
}
}
My Error is :
An object reference is required for the non-static field, method, or property 'GMBL.Program.Start()'
How can I fix it?
Upvotes: 1
Views: 143
Reputation: 2801
Static methods are not associated with a class instance. In your case method C() is a non-static method i.e. it is associated with a class instance and to access C() from a static method you have to first create an object of your class A. Then call C() from that object.
So inside Main() method use below 2 lines
A obj = new A();
obj.C();
Upvotes: 0
Reputation: 35409
change public void c()
to public static void c()
or
Create a new
instance of class A
and call the instance member c();
static void Main ( string [ ] args )
{
var foo = new A();
foo.c();
}
As @SLaks pointed out you cannot call instance members
of a type
from a static member
of the same type
, or some other type
, without a reference of said type
.
Upvotes: 2
Reputation: 9158
Two issues are there in your code.
Issue#1 : You can not use non-static members in static methods.
To use c() in your main method, either you have to change c() to a static method like
public static void c(){....}
OR declare an object for your class A and then call c() with that object instance like
A objA = new A();
objA.c();
Issue#2 : The statement
B = b( );
is wrong because the method b() is not returning any value.
First change
private B;
to
private int B; // Or some thing like this
and then
public void b(){ }
to
public int b(){}
Hope this helps.
Upvotes: 0
Reputation: 21015
first, you can't write private B, you must give be a type. second, b does not return any value, so you can't assign it to B
Upvotes: 0
Reputation: 2206
If you don't want to instantiate a new class, simple make the c
static, example:
public static void c()
Upvotes: 0
Reputation: 16651
Move the Main
function out to another static class, and within it create an instance of A
, and call the method:
class A
{
private B;
public void b(){ }
public void c(){ B = b( );}
}
class Program
{
public static void Main ( string [ ] args )
{
A a = new A();
a.c();
}
}
The app's entry point should generally live in its own independent class.
Upvotes: 0
Reputation: 6188
You have to create an object for your class A.
ClassA a1 = new classA();
a1.c();
Upvotes: 0
Reputation: 152556
You are referencing a non-static function c()
from the static function Main()
. Either make c()
static or create an instance of A
and call c()
on it:
A a = new A();
a.c();
// do something with a
Upvotes: 0
Reputation: 887453
Main
is a static
method – it is not associated with an instance of your class.
c
is an instance method – it operates on an instance of your class.
You can only call c
on an instance.
Upvotes: 6