Classes and objects

In C#, classes and objects are fundamental concepts of object-oriented programming (OOP). They provide a way to define the structure and behavior of objects, which are instances of classes. Here’s an overview of classes and objects in C#:


Classes:

  • A class is a blueprint or template that defines the characteristics and behavior of objects.
  • It encapsulates data (fields) and methods (functions) that operate on that data.
  • Classes serve as the foundation for creating objects.

Example:

class Person

{

    // Fields (data)

    public string name;

    public int age;

    // Methods (behavior)

    public void SayH

ello()

    {

        Console.WriteLine(“Hello, my name is ” + name + ” and I am ” + age + ” years old.”);

    }

}


Objects:

  • An object is an instance of a class, created using the new keyword.
  • It represents a specific entity that possesses the characteristics defined by the class.
  • Objects have their own unique set of field values and can invoke the methods defined in the class.

Example:

Person person1 = new Person();

person1.name = “John”;

person1.age = 25;

person1.SayHello();  // Output: Hello, my name is John and I am 25 years old.