C# Classes and Objects

Introduction

Classes and objects are fundamental concepts in object-oriented programming (OOP). A class is a blueprint or template for creating objects. An object is an instance of a class, containing both data (fields or properties) and methods (functions) that operate on the data.

Classes

A class is a blueprint or template for creating objects. In C#, a class is defined using the class keyword followed by the class name and a pair of curly braces that enclose the class members (fields, properties, methods, etc.).

Syntax

public class ClassName
{
    // Fields
    private dataType fieldName;

    // Properties
    public dataType PropertyName { get; set; }

    // Methods
    public returnType MethodName(parameters)
    {
        // Method body
    }
}

Example

Here’s an example of a simple class definition:

using System;

namespace ClassesAndObjectsExample
{
    public class Car
    {
        // Fields
        private string color;
        private string model;

        // Constructor
        public Car(string color, string model)
        {
            this.color = color;
            this.model = model;
        }

        // Properties
        public string Color
        {
            get { return color; }
            set { color = value; }
        }

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

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

        public void StopEngine()
        {
            Console.WriteLine("Engine stopped.");
        }
    }
}

Objects

An object is an instance of a class. It is created using the new keyword followed by the class constructor.

Creating an Object

ClassName objectName = new ClassName(constructorParameters);

Example

Here’s how to create an object of the Car class and interact with its members:

using System;

namespace ClassesAndObjectsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating an object of the Car class
            Car myCar = new Car("Red", "Toyota");

            // Accessing properties
            Console.WriteLine("Car Model: " + myCar.Model);
            Console.WriteLine("Car Color: " + myCar.Color);

            // Modifying properties
            myCar.Color = "Blue";
            Console.WriteLine("Updated Car Color: " + myCar.Color);

            // Calling methods
            myCar.StartEngine();
            myCar.StopEngine();
        }
    }
}

Output

Car Model: Toyota
Car Color: Red
Updated Car Color: Blue
Engine started.
Engine stopped.

Constructors

Constructors are special methods that are called when an object is instantiated. They initialize the object’s data and allocate memory for the object. In C#, constructors have the same name as the class and do not have a return type.

Syntax

public ClassName(parameters)
{
    // Constructor body
}

Example

public class Person
{
    // Fields
    private string name;
    private int age;

    // Constructor
    public Person(string name, int age)
    {
        this.name = name;
        this.age = age;
    }

    // Properties
    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public int Age
    {
        get { return age; }
        set { age = value; }
    }

    // Methods
    public void DisplayInfo()
    {
        Console.WriteLine("Name: " + Name);
        Console.WriteLine("Age: " + Age);
    }
}

Example Usage

using System;

namespace ClassesAndObjectsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Creating an object of the Person class
            Person person = new Person("Alice", 30);

            // Accessing properties
            Console.WriteLine("Person Name: " + person.Name);
            Console.WriteLine("Person Age: " + person.Age);

            // Modifying properties
            person.Age = 35;
            Console.WriteLine("Updated Person Age: " + person.Age);

            // Calling methods
            person.DisplayInfo();
        }
    }
}

Output

Person Name: Alice
Person Age: 30
Updated Person Age: 35
Name: Alice
Age: 35

Access Modifiers

Access modifiers are keywords used to specify the accessibility of classes, methods, and other members. Common access modifiers in C# include:

  • public: The member is accessible from any code.
  • private: The member is accessible only within the same class.
  • protected: The member is accessible within the same class and by derived class instances.
  • internal: The member is accessible within the same assembly but not from another assembly.
  • protected internal: The member is accessible within the same assembly and by derived class instances.

Example

public class Sample
{
    public int publicField;
    private int privateField;
    protected int protectedField;
    internal int internalField;
    protected internal int protectedInternalField;

    public void DisplayFields()
    {
        Console.WriteLine("Public Field: " + publicField);
        Console.WriteLine("Private Field: " + privateField);
        Console.WriteLine("Protected Field: " + protectedField);
        Console.WriteLine("Internal Field: " + internalField);
        Console.WriteLine("Protected Internal Field: " + protectedInternalField);
    }
}

Example Usage

using System;

namespace AccessModifiersExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Sample sample = new Sample();
            sample.publicField = 10;
            // sample.privateField = 20; // Error: Inaccessible due to protection level
            // sample.protectedField = 30; // Error: Inaccessible due to protection level
            sample.internalField = 40;
            sample.protectedInternalField = 50;

            sample.DisplayFields();
        }
    }
}

Output

Public Field: 10
Private Field: 0
Protected Field: 0
Internal Field: 40
Protected Internal Field: 50

Conclusion

Classes and objects are the building blocks of object-oriented programming in C#. By defining classes, you create blueprints for objects, which encapsulate data and behavior. Understanding how to create and use classes and objects, along with constructors and access modifiers, is fundamental to writing modular, reusable, and maintainable code in C#.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top