C# Example: creating a class, defining properties and methods, instantiating objects, and accessing their members - Biz Tech

C# Example: creating a class, defining properties and methods, instantiating objects, and accessing their members

Listen
 using System;

class Program
{
    static void Main(string[] args)
    {
        Person person1 = new Person("John", 30);
        Person person2 = new Person("Jane", 25);

        person1.SayHello();
        person2.SayHello();

        Console.WriteLine(person1.Name + " is " + person1.Age + " years old.");
        Console.WriteLine(person2.Name + " is " + person2.Age + " years old.");
    }
}

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public void SayHello()
    {
        Console.WriteLine("Hello, my name is " + Name + "!");
    }
}

This example defines a Person class with Name and Age properties and a SayHello() method, creates two Person objects, and accesses their members. The following steps are performed:

  1. Define a Person class with Name and Age properties and a SayHello() method.
  2. Create two Person objects using the new keyword and passing in the name and age as arguments to the constructor.
  3. Call the SayHello() method on both Person objects to output a greeting to the console.
  4. Access the Name and Age properties of both Person objects and output them to the console using Console.WriteLine().

Note that there are many other class-related concepts and operations you can perform, such as inheritance, interfaces, and encapsulation. This example is just one possible multi-step process for working with classes.