SoFunction
Updated on 2025-03-07

Quickly understand c# structure

C# structure

In C#, a structure is a value type data structure. It allows a single variable to store relevant data for various data types. The struct keyword is used to create a structure.

Define structure

struct Books
{
  public string title;
  public string author;
  public string subject;
  public int book_id;
}; 

How to use the structure

public class testStructure
{
  public static void Main(string[] args)
  {

   Books Book1;    /* Declare Book1, type Book */
   Books Book2;    /* Declare Book2, type Book */

   /* book 1 details */
    = "C Programming";
    = "Nuha Ali";
    = "C Programming Tutorial";
   Book1.book_id = 6495407;

   /* book 2 details */
    = "Telecom Billing";
    = "Zara Ali";
    = "Telecom Billing Tutorial";
   Book2.book_id = 6495700;

   /* Print Book1 message */
   ( "Book 1 title : {0}", );
   ("Book 1 author : {0}", );
   ("Book 1 subject : {0}", );
   ("Book 1 book_id :{0}", Book1.book_id);

   /* Print Book2 information */
   ("Book 2 title : {0}", );
   ("Book 2 author : {0}", );
   ("Book 2 subject : {0}", );
   ("Book 2 book_id : {0}", Book2.book_id);   

   ();

  }
}

Class vs Structure

Classes and structures have the following basic differences:

  • Classes are reference types, and structures are value types.
  • Structure does not support inheritance.
  • Structures cannot declare default constructors.

Characteristics of C# structure

You have used a simple structure called Books. The structure in C# is different from that in traditional C or C++. The structure in C# has the following characteristics:

  • Structures can have methods, fields, indexes, properties, operator methods, and events.
  • A structure can define a constructor, but it cannot define a destructor. However, you cannot define a parameterless constructor for a structure. The parameterless constructor (default) is automatically defined and cannot be changed.
  • Unlike classes, structures cannot inherit other structures or classes.
  • Structures cannot be used as the infrastructure of other structures or classes.
  • The structure can implement one or more interfaces.
  • Structure members cannot be specified as abstract, virtual, or protected.
  • When you create a structure object using the New operator, the appropriate constructor is called to create the structure. Unlike classes, structures can be instantiated without using the New operator.
  • If the New operator is not used, the field is assigned and the object is used only after all fields are initialized.

The above is a quick understanding of the detailed content of the c# structure. For more information about the c# structure, please follow my other related articles!