What is the difference between Struct and a Class?

Asked 06-Dec-2019
Viewed 466 times

1 Answer


0

Structs and classes are both user-defined data types in the C# programming language, but they have some key differences.

A struct is a type of value, whereas a class is a type of reference. This means that when a struct is assigned to a variable, a copy of the struct is made, and the variable references that copy. With a class, the variable references the original object, so changes made to the object through one variable will be visible through any other variables that reference the same object. This means that structs have a smaller memory footprint, but it also means that they cannot be used to implement an "object identity" or a "reference identity" behaviour.

Structs also have different default accessibility levels. In C#, structs are internal by default, while classes are private by default. This means that structs can be accessed within the same assembly, while classes can only be accessed within the same class or struct.

Structs cannot inherit from other structs or classes, while classes can inherit from other classes or implement interfaces. This means structs can only use the functionality that is built-in to the struct, while classes can use functionality inherited from other classes.

Structs cannot have explicit parameterless constructors, while classes can have explicit parameterless constructors. This means structs must always have their members initialized when created, while classes can have uninitialized objects.

Structs are useful for small data structures with a well-defined value, such as a point in a 2D space, a colour, a size, etc. They are also useful for performance-critical operations, as they have a smaller memory footprint and can be passed by value, which can be more efficient in certain situations.

On the other hand, classes are useful for larger data structures with more complex behaviour, such as a database connection, a file, a network stream, etc. They are also useful for implementing an "object identity" or a "reference identity" behaviour and inheritance and polymorphism.

In summary, structs and classes are both user-defined data types in the C# programming language, but they have some key differences. Structs are value types, while classes are reference types. Structs are internal by default, while classes are private by default. Structs cannot inherit from other structs or classes, while classes can inherit from other classes or implement interfaces. Structs cannot have explicit parameterless constructors, while classes can have explicit parameterless constructors. Structs are useful for small data structures with a well-defined value, while classes are useful for larger data structures with more complex behaviour.

 


 


advertising