In C#, a class is a blueprint for creating objects. It is a template that defines the properties and behaviors that objects of the class will have.
Here is an example of a simple class in C#:
public class Student
{
// Properties
public string Name { get; set; }
public int Age { get; set; }
// Constructor
public Student(string name, int age)
{
Name = name;
Age = age;
}
// Method
public void PrintInformation()
{
Console.WriteLine($"Name: {Name}, Age: {Age}");
}
}
This class has three parts:
Properties: These are the variables that define the state of the object. In this example, the Student class has two properties: Name and Age.
Constructor: This is a special method that is called when an object of the class is created. It is used to initialize the object's properties. In this example, the Student class has a constructor that takes two arguments: name and age, which are used to initialize the Name and Age properties of the object.
Method: This is a piece of code that performs a specific task. In this example, the PrintInformation method prints the name and age of the student to the console.
To create an object of the Student class, you can use the following code:
Student s = new Student("John", 20);
You can then access the object's properties and call its methods using the dot notation:
string name = s.Name; // name will be "John"
int age = s.Age; // age will be 20
s.PrintInformation(); // prints "Name: John, Age: 20" to the console
Comments
Post a Comment