Algorithm


In C#, a class is a blueprint or a template for creating objects. Objects are instances of classes, and they encapsulate data and behavior. Here's a basic example to illustrate the concept of a class and object in C#:

 

 

Code Examples

#1 Access Class Members using Object in C# Programming

Code - C# Programming

using System;

namespace ClassObject {

  class Dog {
    string breed;

    public void bark() {
      Console.WriteLine("Bark Bark !!");
      
    }

    static void Main(string[] args) {

      // create Dog object 
      Dog bullDog = new Dog();

      // access breed of the Dog 
      bullDog.breed = "Bull Dog";
      Console.WriteLine(bullDog.breed);

      // access method of the Dog
      bullDog.bark();   

      Console.ReadLine();
     
    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Bull Dog
Bark Bark !!

#2 Creating Multiple Objects of a Class in C# Programming

Code - C# Programming

using System;

namespace ClassObject {

  class Employee {

    string department;

    static void Main(string[] args) {

      // create Employee object 
      Employee sheeran = new Employee();

      // set department for sheeran
      sheeran.department = "Development";
      Console.WriteLine("Sheeran: " + sheeran.department);

      // create second object of Employee
      Employee taylor = new Employee();

      // set department for taylor
      taylor.department = "Content Writing";
      Console.WriteLine("Taylor: " + taylor.department);

      Console.ReadLine();
    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Sheeran: Development
Taylor: Content Writing

#3 Creating objects in a different class in C# Programming

Code - C# Programming

using System;

namespace ClassObject {

  class Employee {
    public string name;

    public void work(string work) {
      Console.WriteLine("Work: " + work);
      
    }
  }

  class EmployeeDrive {
    static void Main(string[] args) {

      // create Employee object 
      Employee e1= new Employee();

      Console.WriteLine("Employee 1");

      // set name of the Employee 
      e1.name="Gloria";
      Console.WriteLine("Name: " + e1.name);

      //call method of the Employee
      e1.work("Coding"); 

      Console.ReadLine();
     
    }
  }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Employee 1
Name: Gloria
Work: Coding
Advertisements

Demonstration


C# Programming Class and Object