First, in c# every there is no soch thing as a function. there are methods.
Every method must be a member of a class -
for example:
======================
namespace foo
{
int Add(int x,int y){ return x+y;}
}
======================
will not compile because, in C# "A namespace does not directly contain
members such as fields or methods"
but this does:
======================
namespace foo
{
class Foobar
{
int x = 0;
public Foobar(int n){ x = n;}
public int Add(int y){ return x+y;}
}
}
======================
As the 'Add' method is a member of the class Foobar which is 'directly
contianed' in the foo namespace. But to use it, you need an instance of
Foobar:
for example:
======================
Foobar foobar;
foobar.Add(4);
======================
won't compile: "unassigned local variable 'foobar'"
Now, with regards to static -
A method modified by the keywords 'static' in C# means that you can call the
method without instancing the containing class.
Lets modify the foobar class above:
======================
namespace foo
{
class Foobar
{
int x = 0;
public Foobar(int n){ x = n;}
public int Add(int y){ return x+y;}
public static int Add(int x, int y){ return x+y;}
}
}
======================
this line will work without an actual instance of Foobar:
======================
System.Console.WriteLine(Foobar.Add(1,2));
======================
and it is 'roughly the equivalent of:
======================
Foobar foobar = new Foobar(1);
System.Console.WriteLine(foobar.Add(2));
======================
Now, static methods cannot reference non-static members, or 'Instance
Members' of their containing class.
for example:
======================
namespace foo
{
class Foobar
{
int x = 0;
public static int Add(int y){return x+=y;}
}
}
======================
does not compile: "An object reference is required for the nonstatic field,
method, or property 'foo.Foobar.x'"
x is only available within actual instances of a foobar class where the
static Add method does not belong to the instance but the class definition.
But, you can mark x as static and it becomes available:
======================
namespace foo
{
class Foobar
{
static int x = 0;
public static int Add(int y){return x+=y;}
}
}
======================
The following does compile as x is declared a static member of Foobar. But
tis has a side effect. x belongs now to ALL instances of Foobar changing one
x, changes x through out the application:
======================
System.Console.WriteLine(Foobar.Add(2));
System.Console.WriteLine(Foobar.Add(2));
System.Console.WriteLine(Foobar.Add(4));
======================
outputs:
======================
2
4
8
======================
as the static x is modified on each call.
make sense????