This Angular tutorial helps you get started with Angular quickly and effectively through many practical examples.

C# - Difference Between Class and Struct


In C#, struct and class are both used to define custom data types, use struct for small, immutable data structures and class for larger more complex objects that require reference semantics but they have some key differences.

1. Type

  • Class - A reference type.
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
    
    Person person1 = new Person { FirstName = "John", LastName = "Doe" };
    Person person2 = person1; // Both variables reference the same object
    person2.LastName = "Smith";
    Console.WriteLine(person1.LastName); // Output: Smith

  • Struct - A value type.
    public struct Point
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
    
    Point point1 = new Point { X = 10, Y = 20 };
    Point point2 = point1; // point2 is a copy of point1
    point2.Y = 30;
    Console.WriteLine(point1.Y); // Output: 20
    

2. Memory Allocation

  • Class - Allocated on the heap. Variables hold a reference to the object.
  • Struct - Allocated on the stack (for local variables) or inline (for member variables). Variables hold the actual data.

3. Inheritance

  • Class - Supports inheritance. Can derive from a base class and be a base class for other classes.
  • Struct - Does not support inheritance. Can implement interfaces but cannot inherit from another struct or class.

4. Default Constructor

  • Class - Can have a parameterless constructor. The compiler provides a default constructor if none is defined.
  • Struct - Cannot have an explicitly defined parameterless constructor. The compiler provides an implicit parameterless constructor that initializes all fields to their default values.

5. Nullability

  • Class - Can be null.
  • Struct - Cannot be null (except nullable structs, defined as Nullable<T> or T?).

6. Performance

  • Class - Typically involves more memory allocation and garbage collection overhead.
  • Struct - More memory-efficient for small data structures due to lower overhead.

7. Immutability

  • Class - Usually mutable. However, can be designed to be immutable.
  • Struct - Should generally be immutable (though not enforced by the compiler), to avoid performance issues related to copying.

Prev Next