Classes and Objects
In C#, a class is a blueprint for creating objects. It defines the structure and behavior of the objects that can be created from it.
An object is an instance of a class. It represents a real-world entity and has properties to store data and methods to perform actions.
Let's look at an example:
1// Creating a class called Person
2public class Person
3{
4 // Properties
5 public string Name { get; set; }
6 public int Age { get; set; }
7
8 // Method
9 public void Introduce()
10 {
11 Console.WriteLine("My name is " + Name + " and I am " + Age + " years old.");
12 }
13}
14
15// Creating an instance of the Person class
16Person person = new Person();
17
18// Accessing and setting the properties
19person.Name = "John Doe";
20person.Age = 30;
21
22// Calling the method
23person.Introduce();
In this example, we defined a class called Person
with properties Name
and Age
. We also defined a method called Introduce
that prints the person's name and age. We then created an instance of the Person
class, set the properties, and called the Introduce
method.
Classes and objects are fundamental concepts in object-oriented programming. They allow us to organize and structure our code by representing real-world entities as objects with properties and methods.
xxxxxxxxxx
class Program
{
static void Main(string[] args)
{
// Creating an instance of the Person class
Person person = new Person();
// Accessing and setting the properties
person.Name = "John Doe";
person.Age = 30;
// Calling the method
person.Introduce();
}
}
public class Person
{
// Properties
public string Name { get; set; }
public int Age { get; set; }
// Method
public void Introduce()
{
Console.WriteLine("My name is " + Name + " and I am " + Age + " years old.");
}
}