Hi Mauzi,
Consider this class
public class MyClass
{
public int nonstaticMember = 0; // this one is unique for every instance
public static int staticMember = 0; // this one is shared between
instances
public MyClass()
{
nonstaticMember++; // increase the unique member ( = 1 )
staticMember++; // increase the static member ( = ? )
// the static member is set to 0 before any instances of MyClass is
created
// so for each new MyClass instance, it will increase
}
// this method can only be accessed through a myclass object
public void NonStaticMethod()
{
Console.WriteLine(nonstaticMember);
Console.WriteLine(staticMember);
}
// this method belongs to the class, not to any particular object
public static void StaticMethod()
{
// static methods cannot access non static methods or members
Console.WriteLine(nonstaticMember); // illegal
Console.WriteLine(staticMember);
}
}
From another class you do this:
MyClass myClassObject1 = new MyClass(); // create an instance of MyClass
MyClass myClassObject2 = new MyClass(); // and another instance
// now nonstaticmember for each object is set to 1
// but static member is set to 1, then to 2;
myClassObject1.NonStaticMethod(); // this works as expected
myClassObject2.NonStaticMethod(); // same method, different instance
// myclass objects can't access static members, they belong to the class
myClassObject1.StaticMethod(); // illegal
myClassObject2.StaticMethod(); // illegal
// the class has access to members and methods that are static
MyClass.staticMember++; // you can access static members through the class
MyClass.StaticMethod(); // as well as static methods
// staticmember is now increased to 3
The result of this code will be
1
2
1
2
3
Non-static methods require an instance (an object) that performs the
method.
Non-static members require an instance to be accessed.
Static methods belong to the class and can only be accessed through the
class
Static members belong to the class but can be accessed through instances
of the class as a shared object
As for performance difference. Well they are two completely different
things.
If you want something to be shared between MyClass objects you typically
make the shared value static. If you want to create some methods
performing stuff that doesn't actually belong to any particular object,
you still have to put them inside a class, but you declare the methods
static. In this case it doesn't really make sense to inherit the class or
make instances of it either. The Math class behaves just like that. It
contains a bunch of static methods and a couple of static members (E and
PI). It also has a a constructor declared private. That way noone can
make instances of it. And the class is 'sealed' making it impossible to
derive from it.
Happy coding!
Morten Wennevik [C# MVP]