Struct and Class Differences in C#

This article has been excerpted from book "The Complete Visual C# Programmer's Guide from the Authors of C# Corner".

This article that deals with types introduced the class and struct keywords, and other topics in the chapter illustrate class and struct concepts such as attributes, member variables, member functions, constructors, and destructors. Even with that background information, people often confuse the concepts of class and struct. However, each keyword has distinct uses.

A class is a data structure that contains data members (e.g., constants and fields), function members (e.g., methods, properties, indexers, events, operators, instance constructors, static constructors, and destructors), and nested types. Class types support inheritance.

Struct data types are similar to classes: they represent data structures that can contain data members and function members. Unlike classes, structs are value types and do not require heap allocation. They are always created on the stack. A variable of a type struct directly contains the data of the struct, whereas a variable of a type class contains a reference to the data.

Struct data types are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. Structs should have few data members. They do not require use of inheritance or referential identity, and they can be conveniently implemented using value semantics where assignment copies the value instead of the reference.

The simple types provided by C#, such as int, double, and bool, are in fact all struct types. Just as these predefined types are structs, so is it possible to use structs and operator overloading to implement new "primitive" types in the C# language.


Hope this article would have helped you in understanding difference in structure and class in C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.

Up Next
    Ebook Download
    View all

    FileInfo in C#

    Read by 9.7k people
    Download Now!
    View all