C# Objects and Classes: A Beginner's Guide
Learn the fundamentals of object-oriented programming (OOP) in C#. This comprehensive guide explains objects, classes, their properties and methods, and how to create and use them effectively in your C# programs. We'll cover key concepts like class declarations, object instantiation, and best practices for organizing your code. Perfect for beginners in C#.
Objects and Classes in C#
C# is an object-oriented programming language. This means it uses the concepts of objects and classes to structure and organize code. Understanding objects and classes is fundamental to C# programming.
Objects in C#
An object is a real-world entity, like a car, a person, or a book. In programming, an object represents data (its *state*) and the actions it can perform (its *behavior*). Objects are created at runtime (when your program is running).
Classes in C#
A class is a blueprint or template for creating objects. It defines the structure and behavior of objects of that class. A class specifies the data (fields or properties) and the methods (functions) that define how an object behaves. Objects are instances of a class.
Example 1: Simple Class and Object Creation
public class Student {
public int Id;
public string Name;
}
public class Example {
public static void Main(string[] args) {
Student student = new Student(); // Create a Student object
student.Id = 101;
student.Name = "Alice";
Console.WriteLine(student.Name); // Access the object's properties
}
}
Example 2: `Main` Method in a Separate Class
The `Main` method (the entry point of your program) can be in a different class than the class you're creating an object from. The class needs to be declared as `public` to be accessed from another class.
public class Student {
public int Id;
public string Name;
}
class TestStudent {
public static void Main(string[] args) {
// ... (Create Student object and access properties) ...
}
}
Example 3: Using Methods for Initialization and Display
It is good practice to use methods for initializing and displaying object data. This keeps your class better organized.
public class Student {
public int Id;
public string Name;
public void SetDetails(int id, string name) { this.Id = id; this.Name = name; }
public void DisplayDetails() { Console.WriteLine($"{this.Id} {this.Name}"); }
}
// ... (Main method to demonstrate) ...
Example 4: Employee Information
public class Employee {
// ... (properties for id, name, salary and methods to set and display employee information) ...
}
// ... (Main method to demonstrate) ...