Skip to content

Difference Between Class and Object in C#

Difference Between Class and Object in C#

In C#, classes, and objects are fundamental concepts of object-oriented programming, but they serve different purposes in a program. Here is the difference between class and object:

Difference Between Class and Object in C#

Class

A class is a blueprint or a template for creating objects. It defines the structure, behavior, and attributes that the objects created from it will possess. A class defines the properties (data members) and methods (functions) that the objects of that class will have. In other words, a class is a blueprint for creating instances (objects) with specific characteristics.

Here’s an example of a simple class definition in C#:

public class Person

{

public string Name { get; set; }

public int Age { get; set; }

public void SayHello()

{

Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");

}

}

Object

An object is an instance of a class. It’s a concrete realization of the class’s blueprint. When you create an object from a class, you’re creating a specific “thing” that has its own set of attributes (defined by the class’s properties) and behaviors (defined by the class’s methods). An object represents a specific entity or instance in your program.

Here’s how you create an object from the Person class:

Person person1 = new Person(); 
person1.Name = "Alice"; 
person1.Age = 30; 
person1.SayHello(); 
// Output: Hello, my name is Alice and I am 30 years old.

In this example, person1 is an object of the Person class.

Conclusion

  • A class is a blueprint or template that defines the structure, attributes, and behaviors that objects will have.
  • An object is a specific instance created from a class, possessing the properties and methods defined by that class.

Classes are used to define the structure and behavior of objects, while objects are used to represent and manipulate actual data in your program.

1 thought on “Difference Between Class and Object in C#”

  1. Pingback: 5 Main Difference Between Interface and Abstract Class in C#

Leave a Reply

Your email address will not be published. Required fields are marked *