really newbie quest. can't use methods ...

  • Thread starter Thread starter H
  • Start date Start date
H

H

Ok, this is my code (yep my first program.....)

class MyClass{

private int b(int i)
{
i = 34;
return i;
}

static void Main()
{
Console.WriteLine("Hej");
int a = 3;
int hello = b(a);
}
}

and this won't compile... I get error CS0120 "An objectreferense is needed
for the non-static field, method or attribute MyClass.b(int)"
(maybe not the best translation, but it'll have to do...)

In every example and in my book this is said to be ok, but not for my
compiler. So what am I doing wrong ? If i make b() static it works, why ?
Exactly what does static do ?

TIA
 
Before you call the method b(), you need to create a new instance of MyClass
(new MyClass()), or declare the b() method as static.
 
class MyClass{

private int b(int i)
{
i = 34;
return i;
}

static void Main()
{
Console.WriteLine("Hej");
int a = 3;
int hello = b(a);
}
}

and this won't compile...
In every example and in my book this is said to be ok,
but not for my compiler. So what am I doing wrong ?

What you are doing wrong? You are reading the wrong books :-)

Check out (e.g.) the following page from the C# Programmer's
Reference by Microsoft

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfstaticpg.asp

or (e.g.) the following article

http://www.devarticles.com/art/1/507

or any other C# manual (www.google.com / www.teoma.com).

HTH, Thomas.
 
Peter Rilling said:
Before you call the method b(), you need to create a new instance of MyClass
(new MyClass()), or declare the b() method as static.

Ahhh ! Just like in java. Ok thanks ! now it's working
 
Well, the key idea of object-oriented programming is that methods
(functions) are tied to data objects.

A static method is one that is not tied to a data object. That is, it's
like a function in C.
 
Back
Top