Classes and Objects in C# Programming


Introduction

In C#, classes are blueprints for creating objects. A class defines the properties (fields) and behaviors (methods) that an object created from the class can have. Objects are instances of classes, and they represent specific entities in a program.

This tutorial will cover how to define and create classes and objects in C#, along with an explanation of access modifiers like public, private, protected, and internal.

Defining a Class in C#

A class is defined using the class keyword, followed by the class name and a body enclosed in curly braces. Inside the class, you define fields, properties, methods, and constructors.

Syntax for Defining a Class

    class ClassName
    {
        // Fields
        // Properties
        // Methods
        // Constructors
    }
        

Example: Defining a Class

Let’s define a simple Car class with some fields and a method.

    using System;     class Car
    {
        // Fields
        public string make;
        public string model;
        private int year;         // Constructor
        public Car(string make, string model, int year)
        {
            this.make = make;
            this.model = model;
            this.year = year;
        }         // Method
        public void DisplayCarInfo()
        {
            Console.WriteLine("Car Make: " + make);
            Console.WriteLine("Car Model: " + model);
            Console.WriteLine("Car Year: " + year);
        }
    }
        

Creating Objects in C#

Once a class is defined, you can create objects from it using the new keyword followed by the class constructor.

Syntax for Creating an Object

    ClassName objectName = new ClassName(parameters);
        

Example: Creating an Object

Now, let’s create an object of the Car class and call its method to display information about the car.

    using System;     class Program
    {
        static void Main()
        {
            // Creating an object of the Car class
            Car myCar = new Car("Toyota", "Corolla", 2020);
                   // Calling the method to display car information
            myCar.DisplayCarInfo();
        }
    }
        

Output:

    Car Make: Toyota
    Car Model: Corolla
    Car Year: 2020
        

Access Modifiers in C#

Access modifiers determine the visibility and accessibility of classes, fields, properties, methods, and constructors in C#. They help you control how and where different parts of your program can be accessed.

Common Access Modifiers

  • public: The member is accessible from any other code in the same assembly or another assembly that references it.
  • private: The member is accessible only within the same class or struct.
  • protected: The member is accessible within its class and by derived class instances.
  • internal: The member is accessible only within the same assembly, but not outside it.

Example of Access Modifiers

Let's modify the Car class to demonstrate the use of different access modifiers for fields and methods.

    using System;     class Car
    {
        // public field: Accessible anywhere
        public string make;         // private field: Accessible only within the Car class
        private string model;         // protected field: Accessible within the Car class and derived classes
        protected int year;         // Constructor
        public Car(string make, string model, int year)
        {
            this.make = make;
            this.model = model;
            this.year = year;
        }         // public method: Accessible anywhere
        public void DisplayCarInfo()
        {
            Console.WriteLine("Car Make: " + make);
            Console.WriteLine("Car Model: " + model);
            Console.WriteLine("Car Year: " + year);
        }         // private method: Accessible only within the Car class
        private void UpdateCarModel(string newModel)
        {
            model = newModel;
        }         // internal method: Accessible only within the same assembly
        internal void ChangeCarYear(int newYear)
        {
            year = newYear;
        }
    }     class Program
    {
        static void Main()
        {
            // Creating an object of the Car class
            Car myCar = new Car("Honda", "Civic", 2021);             // Accessing public field and method
            Console.WriteLine("Car Make: " + myCar.make);
            myCar.DisplayCarInfo();             // The following will cause an error:
            // Console.WriteLine(myCar.model);   // Error: model is private
            // myCar.UpdateCarModel("Accord");  // Error: UpdateCarModel is private             // Accessing internal method (if within same assembly)
            myCar.ChangeCarYear(2022);
            Console.WriteLine("Updated Car Year: " + myCar.year);
        }
    }
        

Output:

    Car Make: Honda
    Car Model: Civic
    Car Year: 2021
    Updated Car Year: 2022
        

Explanation

In this example:

  • make is a public field, so it can be accessed from anywhere.
  • model is a private field, so it can only be accessed inside the Car class.
  • year is a protected field, which would be accessible to derived classes (not shown in this example).
  • The UpdateCarModel method is private, so it cannot be called outside the Car class.
  • The ChangeCarYear method is internal, so it can only be accessed within the same assembly.

Conclusion

In this tutorial, we've learned how to define classes and create objects in C#, as well as how to use access modifiers to control the visibility and accessibility of fields, methods, and other members within a class. Understanding how to use these concepts will help you organize and structure your programs effectively while maintaining encapsulation and security of your data.




Advertisement