Difference between struct and class?

 Updated on October 16, 2014     VIKRAM     716

Classes and structs are essentially templates from which you can create objects. Each object contains data and has methods to manipulate and access that data. The class defi nes what data and functionality each particular object (called an instance ) of that class can contain. For example, if you have a class that represents a customer, it might defi ne fi elds such as CustomerID, FirstName, LastName, and Address, which you will use to hold information about a particular customer. It might also define functionality that acts upon the data stored in these fields. You can then instantiate an object of this class to represent one specific customer, set the field values for that instance, and use its functionality.

class PhoneCustomer
{
  public const string DayOfSendingBill = "Monday";
  public int CustomerID;
  public string FirstName;
  public string LastName;
}

Structs differ from classes in the way that they are stored in memory and accessed (classes are reference types stored in the heap; structs are value types stored on the stack), and in some of their features (for example, structs don’t support inheritance). You will tend to use structs for smaller data types for performance reasons. In terms of syntax, however, structs look very similar to classes; the main difference is that you use the keyword struct instead of class to declare them. For example, if you wanted all PhoneCustomer instances to be allocated on the stack instead of the managed heap, you could write:

struct PhoneCustomerStruct
{
  public const string DayOfSendingBill = "Monday";
  public int CustomerID;
  public string FirstName;
  public string LastName;
}

For both classes and structs, you use the keyword new to declare an instance. This keyword creates the object and initializes it; in the following example, the default behavior is to zero out its fields:

  PhoneCustomer myCustomer = new PhoneCustomer(); // works for a class
  PhoneCustomerStruct myCustomer2 = new PhoneCustomerStruct(); // works for a struct

One restriction of using a struct is that structs do not support inheritance, beyond the fact that every struct is automatically derived from System.ValueType. In fact, we should be more careful. It’s true that it is not possible to code a type hierarchy of structs; however, it is possible for structs to implement interfaces. In other words, structs don’t really support implementation inheritance, but they do support interface inheritance. We can summarize the situation for any types that you defi ne as follows:

  • Structs are always derived from System.ValueType . They can also be derived from any number of interfaces.
  • Classes are always derived from one other class of your choosing. They can also be derived from any number of interfaces.

If you enjoyed this post, please like (or) share this article.


Comments