[C#] How do I define and use classes and objects in C#?

To define and use classes and objects in C#, you can follow these steps:

  1. Define a class: Start by creating a new class using the class keyword. You can define properties, methods, and constructors inside the class. Here's an example of a simple class named Person:
 1public class Person
 2{
 3    public string Name { get; set; }
 4    public int Age { get; set; }
 5
 6    public void SayHello()
 7    {
 8        Console.WriteLine($"Hello, my name is {Name} and I'm {Age} years old.");
 9    }
10}
  1. Create an object: To create an object from the class, use the new keyword followed by the class name and parentheses. Assign the object to a variable. Here's an example of creating an object from the Person class:
1Person person1 = new Person();
  1. Set object properties: You can set the properties of an object using the dot notation. Here's an example of setting the Name and Age properties of the person1 object:
1person1.Name = "John";
2person1.Age = 30;
  1. Use object methods: You can call the methods defined in the class using the dot notation. Here's an example of calling the SayHello method on the person1 object:
1person1.SayHello();

Output:

1Hello, my name is John and I'm 30 years old.

By defining classes and creating objects, you can encapsulate data and behavior to create reusable and organized code in C#.