404 Not Found

404 Not Found


nginx

Classes and Objects

Why Classes Are Needed

C# is an object-oriented language where almost everything is an object. We previously wrote code using top-level statements, but real C# programs are built from classes. A class is a blueprint for objects — it defines data (fields) and behavior (methods), while an object is a concrete instance of a class.

Class Definition

Use the class keyword to define a class. Class names use PascalCase (capitalize the first letter of each word).

CSHARP
class Person
{
    public string Name;
    public int Age;

    public void SayHello()
    {
        System.Console.WriteLine($"Hello, I'm {Name}, {Age} years old.");
    }
}

Creating Objects

Use the new keyword to create an object from a class:

CSHARP
Person p = new Person();
p.Name = "Tom";
p.Age = 18;
p.SayHello();
TEXT
Hello, I'm Tom, 18 years old.

Each new creates an independent object with its own copy of fields.

Fields and Field Initialization

Fields can be assigned initial values at declaration:

CSHARP
class Student
{
    public string Name = "Unknown";
    public int Score = 0;
}

If no initial value is assigned, numeric types default to 0, and reference types default to null.

Access modifiers control field visibility:

Modifier Meaning
public Accessible from anywhere
private Only accessible within the class (default)

Typically, fields are set to private and access is controlled through methods or properties.

Example

CSHARP
using System;

class BankAccount
{
    private decimal balance = 1000m;

    public void Deposit(decimal amount)
    {
        balance += amount;
        Console.WriteLine($"Deposited {amount}, balance is {balance}");
    }

    public void ShowBalance()
    {
        Console.WriteLine($"Current balance: {balance}");
    }
}

class Program
{
    static void Main()
    {
        BankAccount acc = new BankAccount();
        acc.ShowBalance();
        acc.Deposit(500m);
    }
}
▶ Try it Yourself
TEXT
Current balance: 1000
Deposited 500, balance is 1500

Methods

Methods are functions defined within a class that describe an object's behavior. Methods can access fields within the same class:

CSHARP
class Calculator
{
    private int result = 0;

    public void Add(int value)
    {
        result += value;
    }

    public int GetResult()
    {
        return result;
    }
}

The this Keyword

this refers to the current object instance. Its most common use is to distinguish fields from parameters with the same name:

CSHARP
class Person
{
    public string Name;
    public int Age;

    public Person(string Name, int Age)
    {
        this.Name = Name;
        this.Age = Age;
    }
}

Constructors

Constructors are called automatically when an object is created, used to initialize the object.

Parameterless Constructor

If no constructor is defined, the compiler automatically generates a parameterless constructor:

CSHARP
class Dog
{
    public string Name;

    public Dog()
    {
        Name = "Unnamed";
    }
}

Parameterized Constructor

CSHARP
class Dog
{
    public string Name;

    public Dog(string name)
    {
        Name = name;
    }
}

⚠️ Once you define any constructor, the compiler will no longer automatically generate a parameterless constructor.

Constructor Overloading

You can define multiple constructors with different parameters:

CSHARP
class Dog
{
    public string Name;
    public int Age;

    public Dog()
    {
        Name = "Unnamed";
        Age = 0;
    }

    public Dog(string name)
    {
        Name = name;
        Age = 0;
    }

    public Dog(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

Constructor Chaining

Use this(...) to have one constructor call another, avoiding code duplication:

CSHARP
class Dog
{
    public string Name;
    public int Age;

    public Dog() : this("Unnamed", 0) { }

    public Dog(string name) : this(name, 0) { }

    public Dog(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

Example

CSHARP
using System;

class Book
{
    public string Title;
    public string Author;
    public decimal Price;

    public Book() : this("Unknown", "Unknown", 0m) { }

    public Book(string title, string author) : this(title, author, 29.9m) { }

    public Book(string title, string author, decimal price)
    {
        Title = title;
        Author = author;
        Price = price;
    }

    public void PrintInfo()
    {
        Console.WriteLine($"\"{Title}\" Author: {Author} Price: {Price}");
    }
}

class Program
{
    static void Main()
    {
        Book b1 = new Book();
        Book b2 = new Book("C# Basics", "Alice");
        Book b3 = new Book("Advanced C#", "Bob", 59.9m);

        b1.PrintInfo();
        b2.PrintInfo();
        b3.PrintInfo();
    }
}
▶ Try it Yourself
TEXT
"Unknown" Author: Unknown Price: 0
"C# Basics" Author: Alice Price: 29.9
"Advanced C#" Author: Bob Price: 59.9

Destructors

A destructor is called before an object is garbage collected. The syntax is ~ClassName():

CSHARP
class Resource
{
    ~Resource()
    {
        Console.WriteLine("Object is being reclaimed");
    }
}

📌 C# has automatic garbage collection (GC), so you rarely need to write a destructor manually. Destructors are only used to release unmanaged resources (such as file handles, database connections), which will be discussed in detail in later lessons.

Object Initializers

C# 3.0 introduced object initializer syntax, which allows you to directly assign values to public fields or properties when using new:

CSHARP
Person p = new Person { Name = "Lily", Age = 20 };

This is equivalent to:

CSHARP
Person p = new Person();
p.Name = "Lily";
p.Age = 20;

Object initializers can be combined with parameterized constructors:

CSHARP
Person p = new Person("Lily") { Age = 20 };

Example

CSHARP
using System;

class Rectangle
{
    public double Width = 1;
    public double Height = 1;

    public double Area()
    {
        return Width * Height;
    }
}

class Program
{
    static void Main()
    {
        Rectangle r1 = new Rectangle();
        Rectangle r2 = new Rectangle { Width = 5, Height = 3 };
        Rectangle r3 = new Rectangle { Width = 10 };

        Console.WriteLine($"r1 area: {r1.Area()}");
        Console.WriteLine($"r2 area: {r2.Area()}");
        Console.WriteLine($"r3 area: {r3.Area()}");
    }
}
▶ Try it Yourself
TEXT
r1 area: 1
r2 area: 15
r3 area: 10

Difference Between new and null

Concept Meaning
new ClassName() Creates an object on the heap, returns a reference to the object
null Does not point to any object, is the default value for reference types
CSHARP
Person p1 = new Person();
Person p2 = null;

Console.WriteLine(p1 == null);
Console.WriteLine(p2 == null);
TEXT
False
True

⚠️ Accessing a member on a null reference throws a NullReferenceException, the most common runtime error in C#:

CSHARP
Person p = null;
p.SayHello();

💡 Check for null before accessing:

CSHARP
if (p != null)
{
    p.SayHello();
}

❓ FAQ

Q What happens if I don't write a constructor?
A The compiler automatically generates a parameterless constructor that assigns default values to fields.
Q Can I still create an object without parameters after defining a parameterized constructor?
A No, unless you manually define a parameterless constructor as well.
Q Can this be used in static methods?
A No, this refers to the current instance, and static methods are not associated with an instance.
Q Can object initializers assign values to private fields?
A No, they can only initialize accessible members (public fields or properties).
Q Are null and 0 the same thing?
A No. null means "no reference", while 0 is a value of numeric types. Value types cannot be null.

📖 Summary

📝 Exercises

  1. Define a Car class with Brand (string) and Speed (int) fields, an Accelerate(int amount) method that increases Speed, and a parameterless constructor that initializes Speed to 0
  2. Add a parameterized constructor Car(string brand) to the Car class, and use this(...) to implement constructor chaining
  3. Use an object initializer to create a Car object and set Brand and Speed, then call the Accelerate method and print the final Speed
  4. Write code demonstrating: create a Car reference assigned to null, try to access its member, use try-catch to catch the NullReferenceException and print a message
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏