When to use a class or struct in C#?

Structs are value types that contain small groups of variables related to each other. An example of a struct could be characteristics of an inventory item or x-y coordinates and a point. In C#, the int, double, bool, and char types are all structs.

An example of a struct:

\\ struct definition
struct Point{
  public int xCoordinate;
  public int yCoordinate;
}

\\ main method - struct instantiation
static void Main(string[] args) {
  Point p;
  p.xCoordinate= 30;
  p.yCoordinate= 20;
}

An example of a class:

\\ class definition
class Person {
  public string Name {get; set;}
  public string Email {get; set;}

  public Person() {
  }

  public Person(string name, string email) {
    this.Name = name;
    this.Email = email;
  }
}

\\ main method - class instantiation
static void Main(string[] args) {
  Person p = new Person("Bob", "bob@email.com");
}

As you can see in the above examples, classes and structs share many things in common and have very similar syntax. Structs, however, are more limited than classes.

1. Instantiation

Classes and structs need to be both instantiated. That means an object or instance of the class or struct must be created.

For classes, it is necessary to use the new keyword when instantiating the class. On the other hand, it is not necessary to use the new keyword when instantiating structs.

2. Inheritance

Classes support inheritance. Structs on the other hand do not support inheritance.

3. Polymorphism

Structs cannot contain virtual methods used in polymorphism whereas classes do.

4. Default Constructor

Structs can not contain default constructors, or constructors without parameters. They can contain, however, parameterized constructors.

Classes on the other hand contain both default constructors and parameterized constructors.

So when to use structs instead of classes?

Structs are better used for simpler data structures, or data that are primary and does not need to be changed after struct object creation.

Classes on the other hand are more complex, contain data intended to be changed after class object creation, and allow the full features of OOP programming like inheritance and polymorphism.

Show Comments