संपादित करें

Objects - create instances of types

Use new to create distinct instances of a class, and assignment to copy a reference to an existing object. In this article, you'll follow those references, distinguish object identity from value equality, and learn when an object's memory can be reclaimed. For class declaration basics, see C# classes.

Follow references to an object

A variable of a class type refers to an object. It doesn't contain a separate copy of the object's state. Two variables can refer to the same object:

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

first and second refer to distinct objects. Each call to new VisitCounter() creates another counter with its own instance fields. An assignment, by contrast, copies a reference:

var alias = first;
alias.AddVisit();
Console.WriteLine(first.GetCount()); // => 2
Console.WriteLine(ReferenceEquals(first, alias)); // => True
Console.WriteLine(first == second); // => False

alias and first refer to one counter. Calling AddVisit through alias changes the count that first.GetCount() returns. See the counter declaration for the complete class.

For value-type assignment, see Structs. Storage location isn't a rule for deciding how assignment behaves.

Object identity vs. value equality

Object identity asks whether two references identify the same object. ReferenceEquals tests identity even when a type supplies its own equality behavior.

Value equality asks whether objects' data compares equal according to their type's rules. An ordinary class uses reference equality by default, but a class can define different equality behavior. A record class provides compiler-generated value equality while remaining a reference type.

Use Equality comparisons for the equality operators, collection-valued members, and guidance on custom equality.

Object lifetime

An object can remain in use after the method that created it returns if other code still holds a reference to it. You don't explicitly destroy class instances. The garbage collector reclaims their memory when they're no longer reachable. See Garbage collection for memory-management details.

Next steps