Skip to main content
CSharpUniversity ASP.NET and C# lessons

The search runs entirely in your browser over the published lesson list.

Class variables compared with instance variables

Two objects from the same class usually hold different values. Occasionally you want a value that all of them share. The difference is one keyword.

Per object, the default

A normal field belongs to each object separately. Change it on one object and the others are untouched.

Per class, when shared

A static field belongs to the class itself. Every object sees the same value, and it exists even before any object is created.

C#
public class Visitor
{
    public string Name;            // per object
    public static int Total;      // shared by all
}
Use static sparingly. Shared state is convenient and easy to abuse. A value that every visitor of a website can change at once is usually a bug waiting to happen.

To keep many classes tidy, you group them into namespaces.

New lessons by email

Leave your address and get a short note whenever a fresh lesson is published. No account needed and you can stop at any time.

Thank you. Your address has been noted in this browser session. Connect a mailing service to deliver the notes for real.