Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Tip
This article is part of the Fundamentals section for developers who already know at least one programming language and are learning C#. If you're new to programming, start with the Get started tutorials first.
Coming from another language? C# instance and static members serve similar purposes to Java instance and class members: they let you work with individual objects or with the type as a whole.
This section builds on the overview of class types to learn how class members store state, provide operations, and control access.
The following example shows examples of different kinds of members that you can add to a class:
public class VisitCounter
{
private int count;
private static int total;
public void AddVisit()
{
count++;
total++;
}
public int GetCount() => count;
public static int GetTotal() => total;
public static int GetTotalExcluding(VisitCounter counter) =>
total - counter.count;
}
You define a type's behavior by declaring its members, the declarations inside a type that describe its data, operations, and nested types. In VisitCounter, the fields count and total store data. Methods such as AddVisit, GetCount, and GetTotal provide operations on that data. In public int GetCount() => count;, the shorthand => count means the method returns the value of count. Both fields and methods are kinds of members you can define in a class. Classes support many other kinds of members, including properties, constructors, and events. The class reference describes the complete declaration syntax.
An instance is an individual object of that class type. Its instance state is the data stored in that object, such as a counter's count. Instance members belong to an individual object: count, AddVisit, and GetCount work with one counter. Static members belong to the type: total and GetTotal track visits across all instances of counters.
The private and public keywords are access modifiers. Access modifiers control which code can access a member.
Instance state and shared state
Use instance members when each object has its own state. Each VisitCounter object has its own count field. Use static members to store shared state or provide operations that aren't associated with a single instance of the type. The static field total stores one value shared by all VisitCounter instances. See the static reference for more details.
The following code demonstrates multiple instances of the VisitCounter and the relationship between instance counts and the total value:
Console.WriteLine(VisitCounter.GetTotal()); // => 0
var first = new VisitCounter();
var second = new VisitCounter();
first.AddVisit();
Console.WriteLine(first.GetCount()); // => 1
Console.WriteLine(second.GetCount()); // => 0
Console.WriteLine(VisitCounter.GetTotal()); // => 1
second.AddVisit();
second.AddVisit();
Console.WriteLine(first.GetCount()); // => 1
Console.WriteLine(second.GetCount()); // => 2
Console.WriteLine(VisitCounter.GetTotal()); // => 3
At the end of this example, first has had one visit and second has had two visits, so their GetCount calls report 1 and 2. The static member GetTotal reports all three visits as 3.
Access instance members through an object reference such as first. Access static members through the type name, as in VisitCounter.GetTotal(). You can use static members even before you create any objects, as the initial call that returns 0 demonstrates.
In an instance method, you can use both instance and static members directly. For example, AddVisit updates the current counter's count and the shared total. A static method has no current instance, so it can't access an instance member without an object reference. GetTotal can be static because it needs only a static field. In contrast, the static method GetTotalExcluding uses the supplied counter reference To calculate the total without one counter's visits:
public static int GetTotalExcluding(VisitCounter counter) =>
total - counter.count;
After the three visits in the example, VisitCounter.GetTotalExcluding(first) returns 2: the shared total of 3 minus first's count of 1.
As you learned in Assignment shares a reference, assignment copies a reference to an existing object. If you give first another name, alias, you still have two counters, not three:
var alias = first;
alias.AddVisit();
Console.WriteLine(first.GetCount()); // => 2
Console.WriteLine(ReferenceEquals(first, alias)); // => True
Console.WriteLine(first == second); // => False
Both alias and first refer to the same counter, so a visit through alias raises first.GetCount() to 2. For an ordinary class that doesn't customize equality, == compares references, not field contents. For data-focused classes with compiler-generated value equality and copy support, see Records.
Static classes
Sometimes you need a group of related operations without any objects to represent. For example, you use Math to perform calculations without creating a Math object:
Console.WriteLine(Math.Abs(-5)); // => 5
For this purpose, declare a static class, a class whose members you use through the type rather than through instances. Use static class for your declaration. A static class can't declare instance members or instance constructors, and you can't create instances of it or derive another class from it. In a non-static class such as VisitCounter, you can combine instance members with static members. For initialization rules and specialized static storage, see Static classes and static class members.
Nested types
A nested type is a type declared inside another type. Use nesting when a type is usually needed only in the context of its containing type. For example, you can declare Entry inside Notebook to keep that supporting type with the class that uses it:
public class Notebook
{
private class Entry
{
public string Text = "";
}
private readonly Entry entry = new Entry();
public void Write(string text) => entry.Text = text;
public string Read() => entry.Text;
}
The declaration of Entry inside Notebook defines the type; it doesn't create any object of that type. To create the Entry object, the Notebook field initializer creates an Entry object for that notebook and assigns it to the entry field.
Nesting places the type's name within its containing type. For more declaration examples, see Nested types.
Continue with other members
Use the following articles for the next part of your class:
- Fields and constants explains stored state, default values,
readonly, and compile-time constants. - Properties explains members that expose values through accessors.
- Methods explains parameters, return values, and calls.
- Constructors explains how an object starts with its initial state.
- Object and collection initializers explains how callers supply initial member values.
- Inheritance explains base and derived classes and inherited members.
Classes can also declare events, indexers, operators, and finalizers. Follow those articles when you need those members rather than add them to every class.