Object-oriented programming (OOP) is a cornerstone of modern software development, and C# is a language built from the ground up to support it. Understanding the fundamental concepts of classes and objects is crucial for writing maintainable, scalable, and efficient C# code. This lesson will provide a comprehensive introduction to defining classes, creating objects (also known as instantiation), and how these concepts form the basis for more advanced OOP principles. Since you're new to OOP, we'll start with the basics and build a solid foundation.
A class is a blueprint or a template for creating objects. It defines the characteristics (data) and behaviors (methods) that objects of that class will have. Think of it like a cookie cutter – the class is the cutter, and the objects are the cookies.
In C#, you define a class using the class keyword, followed by the name of the class and a pair of curly braces {}. Inside the curly braces, you define the members of the class, which can include fields (variables) and methods (functions).
// Defining a simple class named 'Dog'
class Dog
{
// Fields (data)
public string name;
public string breed;
public int age;
// Method (behavior)
public void Bark()
{
Console.WriteLine("Woof!");
}
}
class Dog: This declares a new class named Dog. Class names should typically be PascalCase (e.g., MyClass, Dog).public string name;: This declares a public field named name of type string. The public keyword means that this field can be accessed from anywhere.public string breed;: This declares a public field named breed of type string.public int age;: This declares a public field named age of type int.public void Bark(): This declares a public method named Bark. The void keyword means that this method doesn't return any value.Console.WriteLine("Woof!");: This line inside the Bark method writes "Woof!" to the console.Classes contain members, which are the variables (fields) and functions (methods) that define the class's characteristics and behavior.
Dog class, name, breed, and age are fields.Dog class, Bark is a method.Access modifiers control the visibility and accessibility of class members. Common access modifiers include:
public: Members can be accessed from anywhere.private: Members can only be accessed from within the class itself.