Classes and Objects in C#

 Classes and Objects in C#


In C#, a class is a blueprint or a template for creating objects. An object is an instance of a class. Classes encapsulate data and behavior into a single unit. Here's an example code that demonstrates how to define a class and create objects:


class Person

{

    public string name;

    public int age;


    public void Display()

    {

        Console.WriteLine("Name: {0}, Age: {1}", name, age);

    }

}


Person p1 = new Person();  // creates a new object of the Person class

p1.name = "John";  // assigns "John" to the name property of p1

p1.age = 30;  // assigns 30 to the age property of p1

p1.Display();  // calls the Display method of p1, which prints "Name: John,

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...