Introduction to Classes in C#

Classes are the fundamental building blocks of object-oriented programming in C#. They allow programmers to define the blueprint for creating objects, which are instances of the class. Classes encapsulate data and behavior into a single unit, providing a modular and reusable way to organize the code.

Class Definition in C#

The classes are defined in the following way:

// Define a class called 'Person'
class Person
{
    // Class variables (also known as fields)
    public string Name;
    public int Age;

    // Class method
    public void Greet()
    {
        Console.WriteLine($"Hello, my name is {Name} and I'm {Age} years old.");
    }
}

// Create objects of the 'Person' class
Person person1 = new Person();
person1.Name = "John";
person1.Age = 30;
person1.Greet();  // Output: Hello, my name is John and I'm 30 years old.

Person person2 = new Person();
person2.Name = "Jane";
person2.Age = 25;
person2.Greet();  // Output: Hello, my name is Jane and I'm 25 years old.
  • In the code above, we define a class called 'Person', which has two public class variables: 'Name' (of type 'string') and 'Age' (of type 'int'). We also have a public method called 'Greet()' that prints a greeting using the variables 'Name' and 'Age'.
  • To create objects of the class 'Person', we use the 'new' keyword followed by the class name ('Person'). We then assign values to the variables 'Name' and 'Age' of each object. Finally, we call the 'Greet()' method on each object to display the greeting.
  • Classes provide a way to create multiple instances (objects) with their own unique data, allowing one to create as many objects 'Person' as needed and access their properties and methods independently.

Conclusion

Classes provide a foundation for building complex applications with C#, offering features such as constructors for object initialization, properties for controlled access to class members, and access modifiers for managing visibility. By leveraging classes effectively, it's possible to create modular, maintainable, and scalable code structures.

Suggested Articles
Introduction to Interfaces in C#
Introduction to Namespaces in C#
Introduction to C#
Handling Octet Data Streams in C#
Arne's C# Chronicles and Coding Best Practices
C# and .NET Framework
A Definitive Guide to Singletons in C#