1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - About Value Types and Reference Types

By , About.com Guide

6 of 10

Static and Instance Classes

Static and Instance Classes

In a class there are two types of fields and functions: instance and static. Instance fields are created when an instance of the class is created. Static fields apply only to the class itself. No matter how many instances of a class there are, there is only one instance of that classes' static fields.

Download Example 4.

This has a class test with a default constructor and a second constructor that copies data from another instance of the class. The private static int field has an id assigned to each instance object as it is created. If you step through the code, when the line

test x2 = new test(x) ;
is executed, you'll notice that the two lines
public object y=0;
public object objid = nextid() ;
are run before the second constructor
test(test copy)
is entered.

The static function nextid() returns the value of the static field id and postincrements it. When you are learning objects and classes, the concept of static fields and functions is a bit alien because they apply to the type not an instance. A static class can exist without any instance fields or members.

Download Example 6.

This has a static class test3. This can only have static members as no instances can be created. Members, and properties are accessed by the name of the class itself.

test3.X = 9;
Here X is a static property. Because test3 is a static class, there can be no instance members and everything must be declared static. If you put breakpoints on the static field x and the static constructor body you can see that those are executed sometime before the assignment takes place.

On the next page : Static Constructors and Initializers

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Static and Instance Classes

©2009 About.com, a part of The New York Times Company.

All rights reserved.