← Back to C# Course | Chapter 6: OOP Basics | Lesson 2 of 7

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:

  1. Objects
Syntax
csharp
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

markup
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})");
    }
}
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
  1. Using an object variable that was never created with new, which throws NullReferenceException.
  2. Assuming assigning an object to another variable copies it, when both refer to the same object.
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.