What is the class?
A class in C# is a blueprint for creating objects. It defines the structure and behavior of objects of a specific type. Each object created from a class is an instance of that class, and it has access to the attributes (fields) and behaviors (methods) defined in the class. Here's a step-by-step example illustrating the creation and use of a simple class in C#:
Let's create a class named 'Person' that represents a person with attributes such as name and age.
Step 1: Define the Class
class Person {
// Attributes (fields)
public string Name { get; set; }
public int Age { get; set; }
// Constructor
public Person(string name, int age) {
Name = name;
Age = age;
}
// Method
public void Introduce() {
Console.WriteLine($"Hi, I'm {Name}, and I'm {Age} years old.");
}
}
In this step, we've defined the 'Person' class with attributes 'Name' and 'Age', a constructor to initialize these attributes, and a method Introduce to introduce the person.
Step 2: Create Objects from the Class
class Program {
static void Main(string[] args) {
// Creating objects
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Bob", 30);
// Calling methods
person1.Introduce();
person2.Introduce();
}
}
In this step, we've created a 'Program' class with a 'Main' method. Inside the 'Main' method, we've created two 'Person' objects: 'person1' and 'person2'. We've also called the Introduce method on both objects to introduce the persons.
Step 3: Compile and Run
Compile and run the program. You should see the following output:
Hi, I'm Alice, and I'm 25 years old.
Hi, I'm Bob, and I'm 30 years old.
In this example, we've successfully defined a 'Person' class, created objects from the class, and called methods on those objects. This demonstrates the basic concepts of creating and using classes in C#.
A class can have fields/properties, constructors and methods. Let us have a look at another example of class 'Student1':