MSDN Documentation

Classes and Objects in .NET

Classes and objects are fundamental concepts in object-oriented programming (OOP) and are central to the .NET framework. A class serves as a blueprint for creating objects, which are instances of that class. They encapsulate data (fields or properties) and behavior (methods) that operate on that data.

Defining Classes

In C#, you define a class using the class keyword, followed by the class name. Access modifiers like public or internal determine the visibility of the class.


namespace MyApplication
{
    public class Person
    {
        // Class members go here
    }
}
            

Class Members

Classes can contain various members:

Example: A simple `Car` class


namespace VehicleCatalog
{
    public class Car
    {
        // Fields
        private string _make;
        private string _model;
        private int _year;

        // Constructor
        public Car(string make, string model, int year)
        {
            _make = make;
            _model = model;
            _year = year;
        }

        // Properties
        public string Make
        {
            get { return _make; }
            set { _make = value; }
        }

        public string Model
        {
            get { return _model; }
            set { _model = value; }
        }

        public int Year
        {
            get { return _year; }
            set
            {
                if (value > 1886) // Basic validation
                {
                    _year = value;
                }
            }
        }

        // Method
        public void DisplayInfo()
        {
            Console.WriteLine($"Car: {_year} {_make} {_model}");
        }

        // Another method
        public int GetAge()
        {
            return DateTime.Now.Year - _year;
        }
    }
}
            

Objects and Instances

An object is an instantiation of a class. You create an object using the new keyword followed by the class constructor.


using VehicleCatalog;

// ... inside a method or another class ...

// Create an instance of the Car class
Car myCar = new Car("Toyota", "Camry", 2022);

// Access members of the object
Console.WriteLine($"My car's make: {myCar.Make}");
myCar.DisplayInfo();
int carAge = myCar.GetAge();
Console.WriteLine($"My car is {carAge} years old.");
            

Inheritance

Inheritance is a mechanism where a new class (derived class or child class) inherits properties and methods from an existing class (base class or parent class). This promotes code reusability.


namespace VehicleCatalog
{
    // Base class (or parent class)
    public class Vehicle
    {
        public string Color { get; set; }

        public void StartEngine()
        {
            Console.WriteLine("Engine started.");
        }
    }

    // Derived class (or child class) inheriting from Vehicle
    public class ElectricCar : Vehicle
    {
        public int BatteryCapacity { get; set; }

        public void Charge()
        {
            Console.WriteLine("Charging battery...");
        }
    }
}
            

An instance of ElectricCar will have access to Color property and StartEngine method from the Vehicle class.

Polymorphism

Polymorphism means "many forms." In OOP, it allows objects of different classes to be treated as objects of a common base class. This is often achieved through method overriding.


namespace ShapeExample
{
    public class Shape
    {
        public virtual void Draw() // 'virtual' allows overriding
        {
            Console.WriteLine("Drawing a generic shape.");
        }
    }

    public class Circle : Shape
    {
        public override void Draw() // 'override' implements base class method
        {
            Console.WriteLine("Drawing a circle.");
        }
    }

    public class Square : Shape
    {
        public override void Draw()
        {
            Console.WriteLine("Drawing a square.");
        }
    }

    // ...
    Shape myCircle = new Circle();
    Shape mySquare = new Square();

    myCircle.Draw(); // Output: Drawing a circle.
    mySquare.Draw(); // Output: Drawing a square.
    // ...
}
            

Abstract Classes

Abstract classes cannot be instantiated directly. They are intended to be used as base classes and can contain abstract methods (methods without an implementation) that must be implemented by derived classes.


namespace EmployeeManagement
{
    public abstract class Employee
    {
        public string Name { get; set; }

        public abstract decimal CalculatePay(); // Abstract method, must be implemented

        public void DisplayName()
        {
            Console.WriteLine($"Employee: {Name}");
        }
    }

    public class FullTimeEmployee : Employee
    {
        public decimal HourlyRate { get; set; }
        public int HoursWorked { get; set; }

        public override decimal CalculatePay()
        {
            return HourlyRate * HoursWorked;
        }
    }

    public class PartTimeEmployee : Employee
    {
        public decimal Salary { get; set; }

        public override decimal CalculatePay()
        {
            return Salary / 12; // Assuming monthly pay
        }
    }

    // Cannot do: Employee genericEmployee = new Employee();
    // ...
    FullTimeEmployee ftEmployee = new FullTimeEmployee { Name = "Alice", HourlyRate = 25, HoursWorked = 40 };
    Console.WriteLine($"{ftEmployee.Name} earns: {ftEmployee.CalculatePay()}");
    // ...
}
            

Interfaces

Interfaces define a contract for what a class should do, without providing the implementation. A class can implement multiple interfaces, allowing for a form of multiple inheritance. This is covered in more detail in the Interfaces documentation.