[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:
- 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 namedPerson
:
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}
- 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 thePerson
class:
1Person person1 = new Person();
- Set object properties: You can set the properties of an object using the dot notation. Here's an example of setting the
Name
andAge
properties of theperson1
object:
1person1.Name = "John";
2person1.Age = 30;
- 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 theperson1
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#.