Objects
An object is a real thing made from a class, like an actual house built from a blueprint. You can make many objects from the same class, each with its own details.
In this page:
Syntax
ClassName objectName = new ClassName();
objectName.Field = value;
objectName.MethodName();
ClassName other = new ClassName { Field = value }; // object initializer
Objects
An object is a concrete instance of a class, created with the new keyword. Each object has its own independent copy of the class's instance fields. You can create many objects from the same class, each representing a distinct entity.
Note:
Every object created with
new gets its own memory, so changing one object never affects another.Example: Objects
using System;
class Point
{
public int X;
public int Y;
}
class Program
{
static void Main(string[] args)
{
Point p1 = new Point { X = 1, Y = 2 };
Point p2 = new Point { X = 5, Y = 9 };
Console.WriteLine($"({p1.X}, {p1.Y})");
Console.WriteLine($"({p2.X}, {p2.Y})");
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using an object variable that was never created with
new, which throwsNullReferenceException. - Assuming assigning an object to another variable copies it, when both refer to the same object.
- Comparing two objects with
==and expecting value equality, when it compares references for classes by default.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: