The Difference Between Class & Instance Members

Recently I've run across several instances of confusion regarding class and instance members.

Typically I get a question like "I defined a new method in my class, but the compiler complains when I try to call it. Why?" The code usually looks something like this (C#):

public class MyApp
{
private static int Main(string[] args)
{
int x = foo();
}






private int foo()
{
return
1;
}
}

If you have been around OOP for a while the problem is obvious, however, to others the mystery static doesn't mean a lot.

Class Members

Here's what is going on. The C#/C++/Java keyword static ("shared" in VB.NET) tells the compiler that this method (Main) belongs to the class (or type) not to the instance of the class. Another way of looking at this is that you don't have to create an instance of the object to use a class (static) method. Since the Main method doesn't have an instance associated with it, it cannot refer to any members that aren't also class members. Since foo() isn't declared static, Main can't see it. In C# the static keyword can be applied to fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types.

As a programmer you access class members by pre-pending the class name to the member, i.e. Class.Member, rather than the typical object variable i.e. object.Member.

Class members play a large role in most modern frameworks and are typically used for creating other objects such as:

int i = int.Parse("1");

Another common usage of class members is getting access to a singleton such as the UTF8 encoding:

string result = Encoding.UTF8.GetString(buffer);

The last need for statics is getting access to things not under the control of the framework, typically the operating system or external libraries since they don't have an object oriented approach.

int t = Environment.TickCount;

Instance Members

Since foo() isn't declared static it is an instance member by default (no keyword for non-static). Instance members must have an object instance otherwise they don't exist. To further confuse the issue foo() can see Main() and can call it without specifically indicating the class that Main() belongs to since it is defined in the same class. I.e. the following is valid:

private int foo()
{
        Main(new string[0]);
        return 1;
}

But the following is not:

private int foo()
{
        MyApp app = new MyApp();
        app.Main();
        return 1;
}

Because Main() is not a part of the instance of MyApp.

Summary

To summarize, class members are defined as belonging to the class and only to the class. Instance members belong to an instance of a class. Class members are essentially the globals of object oriented programming and caution should be exercise in the creation of them for the same reasons we know to avoid globals.

1 Comment

Comments have been disabled for this content.